python新线程打开cmd_Python – 函数无法在新线程中运行

我试图使用此函数杀死

Windows上的notepad.exe进程:

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

当我调用这样的函数时,它就像一个魅力:

杀()

但是当在一个新线程中运行该函数时它崩溃了,我不知道为什么.

最佳答案

import thread, wmi, os

import pythoncom

print 'CMD: Kill command called'

def kill():

pythoncom.CoInitialize()

. . .

在线程中运行Windows函数可能很棘手,因为它通常涉及COM对象.使用pythoncom.CoInitialize()通常允许你这样做.另外,您可能需要查看threading库.处理比线程更容易.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值