O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using Automation Objects from Python

As we discussed previously, automation objects are COM objects that expose methods and properties using the IDispatch interface. So how do we use these objects from Python? The win32com.client package contains a number of modules to provide access to automation objects. This package supports both late and early bindings, as we will discuss.

To use an IDispatch-based COM object, use the method win32com.client.Dispatch() . This method takes as its first parameter the ProgID or CLSID of the object you wish to create. If you read the documentation for Microsoft Excel, you’ll find the ProgID for Excel is Excel.Application, so to create an object that interfaces to Excel, use the following code:

>>> import win32com.client
>>> xl = win32com.client.Dispatch("Excel.Application")
>>>

xl is now an object representing Excel. The Excel documentation also says that a boolean property named Visible is available, so you can set that with this code:

>>> xl.Visible = 1
>>>

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required