This article is more than 1 year old

Quick scripting for .NET with IronPython

Office benefits

Rather than continue to use the interactive shell, it's time to write some code so create a text file called wkbs.py. The first thing is to put in place the code we need to grab the path from the command line, or else fall back on a suitable hard-coded default. It also lists the files that it finds for us:


import sys
sys.path.append(r'c:\Python25\lib')

import glob
import os.path
from System.IO import File, FileInfo

if __name__ == '__main__':
  if len(sys.argv)==2:
    wkbdir=sys.argv[1]
  else:
    wkbdir=r'c:\spreadsheets\*.xls*'

wkbs=glob.glob(wkbdir)
print wkbs

Run this by typing ipy wkbs.py <your path> at the command prompt.

Not very interesting yet, and no sign of .NET. So let's make use of some libraries from the System.IO package. Going back to the code let's define a function that lists the workbook name and last accessed date. Add the following to the end of wkbs.py:


def wkbInfo2(w):
  print 'Name: %s, Last Accessed: %s' % (FileInfo(w).Name, File.GetLastAccessTime(w))
  return w

names=[wkbInfo2(wkb) for wkb in wkbs ]
print 'Total files : %d' % len(names)

This prints out the name and last accessed timestamp of each file, along with a count of found files at the end.

But we want more than this, we want to know the number of worksheets and the name of each sheet as well. For this we need to open each workbook in Excel, walk the worksheets collection and then exit cleanly.


def wkbInfo3(w):
  ewb=excel.Workbooks.Open(w)
  print "Name: %s, Number of worksheets: %s" % (ewb.Name, ewb.Worksheets.Count)
  for bk in ewb.Worksheets:
    print '\tSheetName: ' + bk.Name
  ewb.Close(False)
  ewb=None
  return w

import clr
import System
print '\nLinking to Excel...'
clr.AddReference("Microsoft.Office.Interop.Excel")
import Microsoft.Office.Interop.Excel as Excel

excel = Excel.ApplicationClass()
names=[wkbInfo3(wkb) for wkb in wkbs ]
print 'Total files : %d' % len(names)
excel.Quit()
excel=None

Note the house keeping in that code, explicitly setting the workbook and application classes to None to ensure that references are released. Failure to do so means that you can end up with a rogue (and invisible) Excel instance running in the background after the program has finished executing.

As should be clear, IronPython provides a good environment for quickly knocking up scripts that can make full use of existing .NET classes and packages. Even relatively tricky things, like grabbing hold of an Office application, can be accomplished easily enough.

The examples so far, though, are console applications coded in a simple text editor. What if you want something in the way of a GUI? And you want more than notepad? In part two we'll look at IronPythonStudio to see what it's got to offer.®

More about

TIP US OFF

Send us news


Other stories you might like