Main contents

Archive for February 2009

Python with COM

February 5th, 2009

The Win32 extensions for Python have been a lifesaver for me many times.  I consider them one of the best ways of scripting the windows platform.  Unfortunately there’s not as much documentation as one could hope for.

A useful trick I discovered recently is the following.  Say you’re trying to use a COM interface such as Microsoft Message Queuing.  You can create a message queue object as follows:

import win32com, win32com.client
serverInfo = win32com.client.Dispatch("MSMQ.MSMQQueueInfo")

However, the next step requires constants from the messaging API such as MQ_SEND_ACCESS.  These can be made available to win32com.client.constants in two ways.  One involves running makepy, but a more robust alternative is as follows:

import win32com, win32com.client
win32com.client.gencache.EnsureDispatch("MSMQ.MSMQQueueInfo")
win32com.client.gencache.EnsureDispatch("MSMQ.MSMQMessage")
from win32com.client import constants
serverInfo = Dispatch("MSMQ.MSMQQueueInfo")
serverInfo.FormatName = <format name>
return serverInfo.Open(constants.MQ_SEND_ACCESS, constants.MQ_DENY_NONE)

The order is important.  Once EnsureDispatch has been called, win32com.client.constants can be imported and will have the correct values available.

Posted in Programming, python | 1 Comment »