使用 Pylons 和 WMI 时出现“Win32 异常释放 IUnknown at...”错误

And*_*ers 2 python wmi pylons multithreading

我使用 Pylons 结合 WMI 模块对几台机器进行一些基本的系统监控,对于基于 POSIX 的系统,一切都很简单 - 对于 Windows - 不是那么简单。

向 Pylons 服务器发出请求以获取当前 CPU,但是它运行不佳,或者至少与 WMI 模块一起运行。首先,我只是做了(某事)这个:

c = wmi.WMI()
for cpu in c.Win32_Processor():
    value = cpu.LoadPercentage
Run Code Online (Sandbox Code Playgroud)

但是,通过 Pylons ( GET http://ip:port/cpu )访问此模块时出现错误:

raise x_wmi_uninitialised_thread ("WMI returned a syntax error: you're probably running inside a thread without first calling pythoncom.CoInitialize[Ex]")
x_wmi_uninitialised_thread: <x_wmi: WMI returned a syntax error: you're probably running inside a thread without first calling pythoncom.CoInitialize[Ex] (no underlying exception)>
Run Code Online (Sandbox Code Playgroud)

查看http://timgolden.me.uk/python/wmi/tutorial.html,我根据“CoInitialize & CoUninitialize”主题下的示例包装了代码,这使代码工作,但它不断抛出"Win32 exception occurred releasing IUnknown at..."

然后查看http://mail.python.org/pipermail/python-win32/2007-August/006237.html和后续帖子,尝试遵循该帖子 - 但pythoncom._GetInterfaceCount()始终为 20。

我猜这在某种程度上与 Pylons 产生工作线程和类似的废话有关,但是我有点迷失在这里,建议会很好。

提前致谢,

安德斯

编辑:如果你正在做类似的事情,不要打扰 WMI 模块,只需使用http://msdn.microsoft.com/en-us/library/aa394531%28VS.85%29.aspx,你就不用不必担心像这样的线程废话。

小智 5

在“import sys”行之后和“import pythoncom”行之前添加“sys.coinit_flags = 0”。这对我有用,虽然我不知道为什么。

  • 0 == pythoncom.COINIT_MULTITHREADED ; 这会强制 com 线程模型为多线程,如果您正在使用工作线程,这是一个隐含的要求。 (2认同)