Using COM Events in Python

I am trying to make an example application in python that uses some COM objects. I read the famous chapter 12 of Python Programing on Win32, but in connection with this problem, it only states:

All event processing is performed using the normal IConnectionPoint interfaces, and although this is beyond the scope of this book, the standard Python COM framework is fully supported.

Can anyone shed some light on this? I need a simple starter sample. Something like adding code to this sample to catch the OnActivate event for a spreadsheet

 import win32com.client xl = win32com.client.Dispatch("Excel.Application") ... 
+7
python com pywin32
source share
1 answer

I don't have automated Excel, but I'm using some kind of code from the Microsoft Speech API , which might be the same for you to get started:

 ListenerBase = win32com.client.getevents("SAPI.SpInProcRecoContext") class Listener(ListenerBase): def OnRecognition(self, _1, _2, _3, Result): """Callback whenever something is recognized.""" # Work with Result def OnHypothesis(self, _1, _2, Result): """Callback whenever we have a potential match.""" # Work with Result 

and then in the main loop:

  while not self.shutting_down.is_set(): # Trigger the event handlers if we have anything. pythoncom.PumpWaitingMessages() time.sleep(0.1) # Don't use up all our CPU checking constantly 

Edit for more details on the main loop:

When something happens, the callback is not called immediately; instead, you should call PumpWaitingMessages (), which checks to see if there are any events, and then call the appropriate callback.

If you want to do something else while this happens, you need to run the loop in a separate thread (see the streaming module); otherwise it may just sit at the bottom of your script. In my example, I ran it in a separate thread, because I also had a graphical interface; the shutting_down variable is threading.Event, which you can use to stop the loop thread.

+6
source share

All Articles