3

notepad.exeこの関数を使用して、Windowsでプロセスを強制終了しようとしています。

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

しかし、新しいスレッドで関数を実行するとクラッシュし、その理由がわかりません。

4

2 に答える 2

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

スレッドでWindows関数を実行すると、COMオブジェクトが関係することが多いため、注意が必要な場合があります。通常、使用pythoncom.CoInitialize()するとそれが可能になります。また、スレッドライブラリを確認することもできます。スレッドよりも処理がはるかに簡単です。

于 2013-01-20T20:34:43.280 に答える
1

いくつかの問題があります(編集: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 が投稿した解決策にたどり着きます。

于 2013-01-20T20:38:58.553 に答える