所以我一直试图找到一种方法来访问任务管理器。我尝试了一些方法,包括wmi模块和windows任务列表,但都不适合我的需要。 wmi太慢了,当我在使用多处理的东西中多次同时访问它时,任务列表变得太慢了。所以我发现这个脚本运行得很好,但是我不能让它与线程一起工作。
import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_Process")
for objItem in colItems:
print "Name: ", objItem.Name
print "File location: ", objItem.ExecutablePath
这是错误:
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 810, in __bootstrap_inner
self.run()
File "C:\Python27\lib\threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "C:\python practice\stuff.py", line 5, in idk
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
File "C:\Python27\lib\site-packages\pypiwin32-219-py2.7-win32.egg\win32com\cli
ent\__init__.py", line 95, in Dispatch
dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,c
lsctx)
File "C:\Python27\lib\site-packages\pypiwin32-219-py2.7-win32.egg\win32com\cli
ent\dynamic.py", line 114, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
File "C:\Python27\lib\site-packages\pypiwin32-219-py2.7-win32.egg\win32com\cli
ent\dynamic.py", line 91, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.II
D_IDispatch)
com_error: (-2147221008, 'CoInitialize has not been called.', None, None)
答案 0 :(得分:6)
您需要致电CoInitialize()
才能使用win32com.client
:
import pythoncom
import win32com.client as client
pythoncom.CoInitialize()
strComputer = "."
objWMIService = client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_Process")
for objItem in colItems:
print "Name: ", objItem.Name
print "File location: ", objItem.ExecutablePath
有关更多背景信息,请参阅using win32com with multithreading