python中是否有等价的WScript.ConnectObject?

Is there an equivalent of WScript.ConnectObject in python?

我正在重新实现一个简单的 WSH script interacting with a COM object ("CANalyzer.Application" if you must know) in python using win32com. I'm blocked at a point where the script calls ConnectObject 方法来将其处理程序绑定到 COM 对象事件:

Set App = CreateObject("CANalyzer.Application")
Set Measurement = App.Measurement
Wscript.ConnectObject Measurement, "Measurement_"

Sub Measurement_OnInit()
  Set TestFunction = App.CAPL.GetFunction("f")
End Sub

这个处理程序似乎是我唯一可以合法调用 GetFunction 的时刻,在处理程序之外调用它要么没有达到预期的效果,要么抛出异常:

pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147418113), None)

是否有 python 中的 ConnectObject 的等价物,我可以用来绑定到 OnInit() 事件?

感谢@JacobSeleznev,我发现了DispatchWithEvents()方法:

class ApplicationEvents(object):
    def OnQuit(self):
        print("quitting")

app = win32com.client.DispatchWithEvents("CANalyzer.Application", ApplicationEvents)

还有一个 WithEvents() 方法,当在调用 Dispatch() 之后有条件地启用事件处理时,该方法很有用:

app = win32com.client.Dispatch("CANalyzer.Application")
win32com.client.WithEvents(app, ApplicationEvents)

最后说明:为了实际派发事件,需要连续调用 pythoncom.PumpWaitingMessages(),直到处理完所有事件。