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 >>>
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access