[python-win32] Handling COM events in a python thread

Tim Golden mail at timgolden.me.uk
Fri Sep 5 17:13:59 CEST 2008


Ujjaval Suthar wrote:
> Hi all,
> 
> I have a COM control which fires a status event called 
> ProcessingDataAvailable(). The COM control has a method call AddData() 
> with some data parameters.
> 
> Using python, in a simple program, I can instantiate COM object via 
> Dispatch and call AddData() method successfully.
> 
> Now, I want to have a thread which keeps running and listening for 
> ProcessingDataAvailable() event and do some processing in my program.
> 
> Can somebody please give me a simple example code that shows how it can 
> be done? I'm very new to this kind of programming.


Well here's a crude example to get you going. It uses the
MSAgent thingy which I imagine is installed (if little used)
on most Windows machines. Notice that it's launching a thread
to pick up events from a Queue -- the standard Python structure
for communicating between threads.

<code>
import win32com.client
import pythoncom
import Queue
import threading
import time

events = Queue.Queue ()

def do_things_with_events (events):
  while True:
    event = events.get ()
    open ("c:/temp/events.log", "a").write (str (event) + "\n")

class AgentEvents:
  def OnHide (self, character_id, cause):
    events.put (("hide", character_id, cause))

#
# Agent.Control.1 - Win2K characters
# Agent.Control.2 - Office2K characters
#
agent = win32com.client.DispatchWithEvents ("Agent.Control.2", AgentEvents)
agent.Connected = True

def start (name, filename=None, show_immediately=True):
  filename = filename or ("%s.acs" % name)
  agent.Characters.Load (name, filename)
  this_agent = agent.Characters (name)
  this_agent.Show ()

if __name__ == '__main__':
  import time
  threading.Thread (target=do_things_with_events, args=(events,)).start ()
  start ("merlin")
  while True:
    pythoncom.PumpWaitingMessages ()
    time.sleep (0.1)

</code>



More information about the python-win32 mailing list