Python - 函数无法在新线程中运行 [英] Python - Function is unable to run in new thread

查看:35
本文介绍了Python - 函数无法在新线程中运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用此函数终止 Windows 上的 notepad.exe 进程:

I'm trying to kill the notepad.exe process on windows using this function:

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

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

It works like a charm when I'm calling the function like this:

kill()

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

But when running the function in a new thread it crashes and I have no idea why.

推荐答案

import  thread, wmi, os
import pythoncom
print 'CMD: Kill command called'
def kill():
    pythoncom.CoInitialize()
    . . .

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

Running Windows functions in threads can be tricky since it often involves COM objects. Using pythoncom.CoInitialize() usually allows you do it. Also, you may want to take a look at the threading library. It's much easier to deal with than thread.

这篇关于Python - 函数无法在新线程中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆