Skip to content

Instantly share code, notes, and snippets.

@maxhk
Last active March 7, 2022 05:57
Show Gist options
  • Save maxhk/b935396b6af476d27ce0 to your computer and use it in GitHub Desktop.
Save maxhk/b935396b6af476d27ce0 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)
@maxhk
Copy link
Author

maxhk commented Jun 18, 2015

Example usage (paste in iPython notebook cell)

%%iron --interop

excel.Visible, excel.DisplayAlerts = True, False

workbook = excel.Workbooks.Add()
ws = workbook.Worksheets[1]
c = ws.Range('A1')

# emails = outlook.ActiveExplorer().Selection
emails  = outlook.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox).Items

for email in emails:
    try:
        c.value = email.Subject
        c.Offset(0, 1).value = email.ReceivedTime
        c.Offset(0, 2).value = email.SenderName
        c = c.Offset(1, 0)

    except:
        pass

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment