1

我正在尝试使用以下脚本杀死作为 python 脚本的一部分在我的系统上运行的任何 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 模块?

4

1 回答 1

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()通常不会像 shell 那样处理您的命令,并且不会将其解析为单独的参数。有关完整说明,请参阅常用参数

如果您必须依赖 shell 解析您的命令,请将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测试恰好适用于小整数,但不是测试整数相等的正确方法。

于 2012-09-21T11:20:52.040 回答