微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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,os
import pythoncom
print 'CMD: Kill command called'
def kill():
    pythoncom.CoInitialize()
    . . .

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐