Skip to content

Instantly share code, notes, and snippets.

@ingted
Forked from maxhk/iron_magic.py
Created March 7, 2022 05:57
Show Gist options
  • Save ingted/97f95d25346492d4ce51d1098553af94 to your computer and use it in GitHub Desktop.
Save ingted/97f95d25346492d4ce51d1098553af94 to your computer and use it in GitHub Desktop.
IronPython magic for iPython notebook
from __future__ import print_function
from IPython.core.magic import register_cell_magic
import subprocess as sp
import tempfile
import os
IRON_PYTHON_PATH = r'C:\HOMEWARE\IronPython-2.7.5\ipy64.exe'
@register_cell_magic
def iron(line, cell):
interop_imports = '''import clr
clr.AddReferenceByName('Microsoft.Office.Interop.Excel, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c')
clr.AddReferenceByName('Microsoft.Office.Interop.Outlook, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c')
from Microsoft.Office.Interop import Excel, Outlook
outlook = Outlook.ApplicationClass()
excel = Excel.ApplicationClass()
'''
try:
with tempfile.NamedTemporaryFile(suffix='.py', delete=False) as fp:
if '--interop' in line:
fp.write(interop_imports)
fp.write(cell)
p = sp.Popen([IRON_PYTHON_PATH, fp.name],
bufsize=64,
stdin=sp.PIPE,
stderr=sp.PIPE,
stdout=sp.PIPE)
errors = p.stderr.read()
if errors.strip() != '':
print(errors, file=sys.stderr)
print(p.stdout.read())
finally:
os.remove(fp.name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment