为什么此脚本无法与python线程一起使用 [英] why does this script not work with threading python

查看:176
本文介绍了为什么此脚本无法与python线程一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一直在尝试找到一种访问任务管理器的方法.我尝试了几种方法,包括wmi模块和Windows任务列表,但都不适合我的需要. wmi太慢了,而当我使用多处理功能同时访问它多次时,tasklist也变得太慢了.所以我发现这个脚本工作得很好,但是我无法使其与线程一起工作.

so i've been trying to ifnd a way to access task manager. I've tried a few methods including the wmi module and the windows tasklist but neither suit my need. wmi is way too slow and tasklist becomes too slow when i access it multiple times concurrently in something using multiprocessing. so i found this script which works quite nicely but i can't get it to work with threading.

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)

推荐答案

您需要调用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

有关更多背景信息,请参见结合使用win32com和多线程

For more background information see using win32com with multithreading

这篇关于为什么此脚本无法与python线程一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆