您的位置:首页 > 编程语言 > Python开发

[转载] python在子线程中使用WMI报错

2016-10-08 11:22 316 查看
本文转载自: http://www.68idc.cn/help/jiabenmake/python/20150123184163.html

我在一个python脚本中用到了WMI,用于确保杀死超时却未能自己结束的进程 (已经先尝试了Ctrl+Break中止)。

测试代码运行正常,但当我把这个函数放在子线程中使用时,却发现报错:


com_error: (-2147221020, 'Invalid syntax', None, None)


后来在网上检索,发现必须添加初始化函数和去初始化函数,所以在一个子线程中可使用的函数代码类似于:

import win32com.client
import pythoncom
import subprocess
import logging
def task_kill_timeout(timeout):
pythoncom.CoInitialize()
WMI = win32com.client.GetObject('winmgmts:')
all_process = WMI.ExecQuery('SELECT * FROM Win32_Process where Name="aaa.exe" or Name="bbb.exe" or Name="ccc.exe"')
for process in all_process:
t = process.CreationDate
t = t[:t.find('.')]
start_time = time.strptime(str(t), '%Y%m%d%H%M%S' )
time_passed_by = time.time() - time.mktime(start_time)
if time_passed_by > timeout:
logging.error( 'Run taskkill %s' % process.name)
print 'Run taskkill %s' % process.name
subprocess.Popen('taskkill /F /pid %s' % process.processid,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
)
time.sleep(1.0)
pythoncom.CoUninitialize ()


一旦上述aaa.exe,bbb.exe,ccc.exe进程运行超过timeout秒,即会被强制结束。

参考链接:
http://bytes.com/topic/python/answers/608938-importing-wmi-child-thread-throws-error
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: