简体   繁体   English

使用Python的subprocess.call来杀死firefox进程

[英]Using Python's subprocess.call to kill firefox process

I am trying to kill any firefox processes running on my system as part of a python script, using the script below: 我试图使用下面的脚本杀死在我的系统上运行的任何firefox进程作为python脚本的一部分:

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

I am encountering the following error as shown below, however 'killall -9 firefox-bin' works whenever I use it directly in the terminal without any errors. 我遇到如下所示的以​​下错误,但是只要我在终端中直接使用它而没有任何错误,“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

Am I missing something or should I be trying to use a different python module altogether? 我错过了什么或者我应该尝试使用不同的python模块吗?

You need to separate the arguments when using subprocess.call : 使用subprocess.call时需要分隔参数:

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

call() normally does not treat your command like the shell does, and it won't parse it out into the separate arguments. call()通常不像shell那样处理你的命令,也不会将它解析为单独的参数。 See frequently used arguments for the full explanation. 有关完整说明,请参阅常用参数

If you must rely on shell parsing of your command, set the shell keyword argument to True : 如果必须依赖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!' )

Note that I changed your test to > 0 to be clearer about the possible return values. 请注意,我将测试更改为> 0以更清楚地了解可能的返回值。 The is test happens to work for small integers due to an implementation detail in the Python interpreter, but is not the correct way to test for integer equality. 由于Python解释器中的实现细节, is测试恰好适用于小整数,但不是测试整数相等性的正确方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM