Kill a running subprocess call
Well, there are a couple of methods on the object returned by subprocess.Popen()
which may be of use: Popen.terminate()
and Popen.kill()
, which send a SIGTERM
and SIGKILL
respectively.
For example...
import subprocessimport timeprocess = subprocess.Popen(cmd, shell=True)time.sleep(5)process.terminate()
...would terminate the process after five seconds.
Or you can use os.kill()
to send other signals, like SIGINT
to simulate CTRL-C, with...
import subprocessimport timeimport osimport signalprocess = subprocess.Popen(cmd, shell=True)time.sleep(5)os.kill(process.pid, signal.SIGINT)
p = subprocess.Popen("echo 'foo' && sleep 60 && echo 'bar'", shell=True)p.kill()
Check out the docs on the subprocess
module for more info: http://docs.python.org/2/library/subprocess.html
You can use two signals to kill a running subprocess call i.e., signal.SIGTERM and signal.SIGKILL; for example
import subprocessimport osimport signalimport time..process = subprocess.Popen(..)..# killing all processes in the groupos.killpg(process.pid, signal.SIGTERM)time.sleep(2)if process.poll() is None: # Force kill if process is still alive time.sleep(3) os.killpg(process.pid, signal.SIGKILL)