Feeds

Quick scripting for .NET with IronPython

Office benefits

HP ProLiant Gen8: Integrated lifecycle automation

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.®

Top three mobile application threats

More from The Register

next story
Apple fanbois SCREAM as update BRICKS their Macbook Airs
Ragegasm spills over as firmware upgrade kills machines
HIDDEN packet sniffer spy tech in MILLIONS of iPhones, iPads – expert
Don't panic though – Apple's backdoor is not wide open to all, guru tells us
Mozilla fixes CRITICAL security holes in Firefox, urges v31 upgrade
Misc memory hazards 'could be exploited' - and guess what, one's a Javascript vuln
NO MORE ALL CAPS and other pleasures of Visual Studio 14
Unpicking a packed preview that breaks down ASP.NET
Captain Kirk sets phaser to SLAUGHTER after trying new Facebook app
William Shatner less-than-impressed by Zuck's celebrity-only app
Cheer up, Nokia fans. It can start making mobes again in 18 months
The real winner of the Nokia sale is *drumroll* ... Nokia
EU dons gloves, pokes Google's deals with Android mobe makers
El Reg cops a squint at investigatory letters
Chrome browser has been DRAINING PC batteries for YEARS
Google is only now fixing ancient, energy-sapping bug
prev story

Whitepapers

Designing a Defense for Mobile Applications
Learn about the various considerations for defending mobile applications - from the application architecture itself to the myriad testing technologies.
How modern custom applications can spur business growth
Learn how to create, deploy and manage custom applications without consuming or expanding the need for scarce, expensive IT resources.
Reducing security risks from open source software
Follow a few strategies and your organization can gain the full benefits of open source and the cloud without compromising the security of your applications.
Boost IT visibility and business value
How building a great service catalog relieves pressure points and demonstrates the value of IT service management.
Consolidation: the foundation for IT and business transformation
In this whitepaper learn how effective consolidation of IT and business resources can enable multiple, meaningful business benefits.