I am calling a command using
subprocess.call(cmd, shell=True)
The command won't terminate automatically. How to kill it?
Since subprocess.call
waits for the command to complete, you can't kill it programmatically. Your only recourse is to kill it manually via an OS specific command like kill
.
If you want to kill a process programmatically, you'll need to start the process with subprocess.Popen
and then terminate
it. An example of this is below:
import time, subprocess
t1 = time.time()
p = subprocess.Popen('sleep 1', shell=True)
p.terminate()
p.wait()
t2 = time.time()
print(t2 - t1)
This script takes about .002s
to execute (rather than ~1s if the sleep command wasn't terminated).
I think what you're looking for is subprocess.terminate()
. If, instead of call
you use Popen
, it's non blocking and you'll be able to resume execution. Of course, if you call terminate
right after, it'll terminate before it does anything.
Documentation here