【问题标题】:Python - Function is unable to run in new threadPython - 函数无法在新线程中运行
【发布时间】:2013-01-20 20:04:59
【问题描述】:

我正在尝试使用此函数杀死 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

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

kill()

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

【问题讨论】:

  • 当你说“它崩溃了”时,你到底是什么意思?

标签: python multithreading wmi


【解决方案1】:
import  thread, wmi, os
import pythoncom
print 'CMD: Kill command called'
def kill():
    pythoncom.CoInitialize()
    . . .

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

【讨论】:

    【解决方案2】:

    有几个问题(编辑:自从我开始回答以来,第二个问题已由“MikeHunter”解决,所以我将跳过它):

    首先,您的程序在启动线程后立即结束,并带走线程。我会假设这不是一个长期的问题,因为大概这将成为更大事情的一部分。为了解决这个问题,您可以通过在脚本末尾添加一个 time.sleep() 调用来模拟其他保持程序运行的东西,例如 5 秒作为睡眠时长。

    这将允许程序给我们一个有用的错误,在你的情况下是:

    CMD: Kill command called
    Unhandled exception in thread started by <function kill at 0x0223CF30>
    Traceback (most recent call last):
      File "killnotepad.py", line 4, in kill
        c = wmi.WMI ()
      File "C:\Python27\lib\site-packages\wmi.py", line 1293, in connect
        raise x_wmi_uninitialised_thread ("WMI returned a syntax error: you're probably running inside a thread without first calling pythoncom.CoInitialize[Ex]")
    wmi.x_wmi_uninitialised_thread: <x_wmi: WMI returned a syntax error: you're probably running inside a thread without first calling pythoncom.CoInitialize[Ex] (no underlying exception)>
    

    如您所见,这揭示了真正的问题,并将我们引向 MikeHunter 发布的解决方案。

    【讨论】:

      猜你喜欢
      • 2019-02-02
      • 2018-09-29
      • 2023-04-09
      • 1970-01-01
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      • 2013-03-16
      • 1970-01-01
      相关资源
      最近更新 更多