简体   繁体   中英

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:

    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.

       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?

You need to separate the arguments when using 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. 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 :

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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