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库.处理比线程更容易.

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...