use*_*290 3 python wmi multithreading
我正在尝试notepad.exe使用此函数终止Windows上的进程:
import thread, wmi, os
print 'CMD: Kill command called'
def kill():
c = wmi.WMI ()
Commands=['notepad.exe']
if Commands[0]!='All':
print 'CMD: Killing: ',Commands[0]
for process in c.Win32_Process ():
if process.Name==Commands[0]:
process.Terminate()
else:
print 'CMD: trying to kill all processes'
for process in c.Win32_Process ():
if process.executablepath!=inspect.getfile(inspect.currentframe()):
try:
process.Terminate()
except:
print 'CMD: Unable to kill: ',proc.name
kill() #Works
thread.start_new_thread( kill, () ) #Not working
Run Code Online (Sandbox Code Playgroud)
当我调用这样的函数时,它就像一个魅力:
kill()
但是当在一个新线程中运行该函数时它崩溃了,我不知道为什么.
import thread, wmi, os
import pythoncom
print 'CMD: Kill command called'
def kill():
pythoncom.CoInitialize()
. . .
Run Code Online (Sandbox Code Playgroud)
在线程中运行Windows函数可能很棘手,因为它通常涉及COM对象.使用pythoncom.CoInitialize()通常允许你这样做.另外,您可能需要查看线程库.处理比线程更容易.