1

我必须从具有描述的 COM API 获取事件:

HRESULT OnStatusMessage(
    [in] IDispatch* pStatusMessage
);

而IStatusMessage有属性:BSTR描述、LONG Code等。

我的代码不起作用:

import msvcrt
import pythoncom
from win32com.client import DispatchWithEvents

class evt(object):
    def OnConnectionLost(self):
        print 'method ConnectionLost'
    def OnStatusMessage(self, s):
        print 'method OnStatusMessage: '  + str(s.Description)
    def OnLogin(self, l):
        print 'method OnLogin:', l
    def OnMessage(self, msg):
    print 'method OnMessage'


session = DispatchWithEvents("NiApi.SrvrSession", evt)
# login settings....

session.Connect()

while 1:
    if msvcrt.kbhit():
    msvcrt.getch()
        session.Disconnect()
        break
    pythoncom.PumpWaitingMessages()

模块因回溯而失败:

Traceback (most recent call last):
  File "C:\Python\AP_272\lib\site-packages\win32com\server\policy.py", line 277, in     _Invoke_
    return self._invoke_(dispid, lcid, wFlags, args)
  File "C:\Python\AP_272\lib\site-packages\win32com\server\policy.py", line 282, in _invoke_
    return S_OK, -1, self._invokeex_(dispid, lcid, wFlags, args, None, None)
  File "C:\Python\AP_272\lib\site-packages\win32com\server\policy.py", line 585, in _invokeex_
    return func(*args)
  File "d:\niapi.py", line 13, in OnStatusMessage
    print 'method OnStatusMessage' + str(s.Description)
AttributeError: 'PyIDispatch' object has no attribute 'Description'
pythoncom error: Python error invoking COM method.

为什么我不能得到这个属性?

4

1 回答 1

3

我在这里找到了答案:

需要调度这个对象:

message = Dispatch(s)
print 'method OnStatusMessage', str(message.Description)

并且不要忘记导入Dispatch

from win32com.client import Dispatch
于 2012-09-14T12:01:22.910 回答