Quick Start to Client side COM and Python

Introduction

This documents how to quickly start using COM from Python. It is not a thorough discussion of the COM system, or of the concepts introduced by COM.

For more details information on Python and COM, please see the COM Tutorial given by Greg Stein and Mark Hammond at SPAM 6 (HTML format) or download the same tutorial in PowerPoint format.

For information on implementing COM objects using Python, please see a Quick Start to Server side COM and Python

We discuss the following topics:

Quick Start

To use a COM object from Python

import win32com.client # Python 1.4 requires "import ni" first.
o = win32com.client.Dispatch("Object.Name")
o.Method()
print o.property

Example

o = win32com.client.Dispatch("Excel.Application")
o.Visible = 1
o.Workbooks.Add() # for office 97 – 95 a bit different!

How do I know which objects are available?

Good question. This is hard! You need to use the documentation with the products, or possibly a COM browser. Note however that COM browsers typically rely on these objects registering themselves in certain ways, and many objects to not do this. You are just expected to know.

The Python COM browser

PythonCOM comes with a basic COM browser that may show you the information you need. Note that this package requires Pythonwin (ie, the MFC GUI environment) to be installed for this to work.

To run the browser, simply double-click on the file "win32com\client\combrowse.py"

Static Dispatch/Type Safe objects

The win32com package has the concept of "static dispatch" objects (or "type safe" objects). The technique above is known as "dynamic dispatch".

In a nutshell, Static Dispatch involves the generation of a .py file that contains support for the specific object. For more information, please see the SPAM 6 COM Tutorial.

The process for generating the .py files is somewhat convoluted and complicated, but the results can be worthwhile. Note that volunterrs to integrate this process with a GUI environment would be appreciated. The "tlbrowse.py" utility (see below) or COM browse utility would be a good start.

To generate Python Sources supporting a COM object

Locate the type information for the COM Server

Again, this can be hard. There are 2 techniques

Generate the code

Start a Command Prompt (ie, a DOS Box)

Run the command:

\Python\Python.exe \python\win32com\client\makepy.py {full path to Type Info} > \python\somename.py

Example. Please change the paths accordingly.

cd "\program files\Microsoft Office\Office"
\python\python.exe \python\win32com\client\makepy.py msword8.olb > \python\msword8.py

Use the code

msword8.py is now a valid Python file which can be imported and used. Note that this may be huge, and therefore the first time it is imported the .pyc generation may take significant time. Subsequent imports will still be very fast.

The .py file should be quite readable, and can effectively document the object model of the particular server.