May 21, 2013

Using COM constants in Python

The Python library win32com allows you to instantiate and manipulate COM objects transparently from Python. One aspect which is not automatic is the treatment of constants, for example the following code will generate an error unless you've performed some necessary steps.
import win32com.client
xl = win32com.client.Dispatch(“Excel.Application”)
print win32com.client.constants.xlWorkbookNormal
To make this work you first need to run the script makepy.py passing the relevant COM type in the command line.
C:\Python27\Lib\site-packages\win32com\client>makepy.py "Excel.Application"
After this step the above Python code should print -4143.