2012-09-21 42 views
1

我想殺死我的系統上運行的python腳本的一部分的任何Firefox的過程中,使用下面的腳本:使用Python的subprocess.call殺Firefox進程

if subprocess.call([ "killall -9 firefox-bin" ]) is not 0: 
     self._logger.debug('Firefox cleanup - FAILURE!') 
    else: 
     self._logger.debug('Firefox cleanup - SUCCESS!') 

我遇到以下錯誤的如下所示,然而'killall -9 firefox-bin'只要我在終端中直接使用它就沒有任何錯誤。

 Traceback (most recent call last): 
File "./pythonfile", line 109, in __runMethod 
if subprocess.call([ "killall -9 firefox-bin" ]) is not 0: 
File "/usr/lib/python2.6/subprocess.py", line 478, in call 
p = Popen(*popenargs, **kwargs) 
File "/usr/lib/python2.6/subprocess.py", line 639, in __init__ 
errread, errwrite) 
File "/usr/lib/python2.6/subprocess.py", line 1228, in _execute_child 
raise child_exception 
OSError: [Errno 2] No such file or directory 

我缺少的東西或我應該試圖完全使用不同的Python模塊?

回答

3

您需要的參數分開使用subprocess.call時:

if subprocess.call([ "killall", "-9", "firefox-bin" ]) > 0: 
    self._logger.debug('Firefox cleanup - FAILURE!') 
else: 
    self._logger.debug('Firefox cleanup - SUCCESS!') 

call()像外殼程序通常不把你的命令,也不會解析出來到單獨的參數。完整的解釋請參閱frequently used arguments

如果你必須依靠你的命令的外殼解析,該shell關鍵字參數設置爲True

if subprocess.call("killall -9 firefox-bin", shell=True) > 0: 
    self._logger.debug('Firefox cleanup - FAILURE!') 
else: 
    self._logger.debug('Firefox cleanup - SUCCESS!') 

請注意,我改變了你的測試> 0更清晰有關可能的返回值。由於Python解釋器中的實現細節,is測試恰好適用於小整數,但是而不是是測試整數相等性的正確方法。

+0

作爲一個側面說明,你應該鼓勵OP使用'...!= 0',而不是'是不是0',而在第二種情況下,('殼= TRUE'),您不再需要名單。傳遞一個字符串就好了。 – mgilson

+0

@mgilson:最好是實際使用'> 0'。 –

+0

夠公平的。我更擔心''is'只能作爲Cpython實現細節使用小整數。但是,我想如果你想多走一步,並且真正考慮在無符號的1字節整數中哪些返回碼是合法的,我想這是合理的。 :) – mgilson