2013-01-20 46 views
3

我想殺了使用此功能的窗口notepad.exe過程:Python的 - 功能無法在新的線程中運行

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()

但在一個新的線程運行函數時崩潰,我不知道爲什麼。

+8

當你說「它崩潰」時,你究竟是什麼意思? – NPE

回答

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

在線程中運行Windows函數可能會非常棘手,因爲它通常涉及COM對象。使用pythoncom.CoInitialize()通常可以讓你做到這一點。此外,你可能想看看threading庫。處理比線程容易得多。

1

有幾個問題(編輯:因爲開始我回答第二個問題已經解決,通過「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的解決方案。