2

下面的代码工作正常。我找不到将一些参数传递给EventHandler或调用MainClassfrom的方法的方法EventHandler。例如,我不想使用 constant param,而是想通过构造函数或 setter 方法传递它。我已经尝试过这里的建议。但在这种情况下EventHandler,实例不会捕获任何事件(或者至少在标准输出中没有出现任何事件)。

class EventHandler:
    param = "value"    
    def OnConnected(self):
        print 'connected'
        return True

class MainClass:
    def run(self):
        pythoncom.CoInitialize()
        session = win32com.client.Dispatch("Lib.Obj")
        session_id = pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch, session)
        args = { 's_id': session_id, }
        thread = threading.Thread(target=self.run_in_thread, kwargs=args)
        thread.start()

    def run_in_thread(self, s_id):
        pythoncom.CoInitialize()
        session = win32com.client.DispatchWithEvent(
            pythoncom.CoGetInterfaceAndReleaseStream(s_id, pythoncom.IID_IDispatch),
            EventHandler
        )
        session.connect()
        while True:
            pythoncom.PumpWaitingMessages()
            time.sleep(1)

if __name__ == '__main__':
    obj = MainClass()
    obj.run() 
4

1 回答 1

3

一种可能性是使用WithEvents函数。但这可能不是最好的方法。现在handlerclient对象也是不同的实体,所以这导致了它们之间的额外交互机制。

class EventHandler:

    def set_params(self, client):
        self.client = client

    def OnConnected(self):
        print  "connected!"
        self.client.do_something()
        return True

client = win32com.client.Dispatch("Lib.Obj")
handler = win32com.client.WithEvents(client, EventHandler)
handler.set_client(client)

client.connect()

while True:
    PumpWaitingMessages()
    time.sleep(1)

这是一个完整的例子

于 2015-10-19T10:48:10.670 回答