I am calling a command using
subprocess.call(cmd, shell=True)
The command won't terminate automatically. How to kill it?
Popen(args) with args as a sequence of program arguments or a single string to execute a child program in a new process with the supplied arguments. To terminate the subprocess, call subprocess. Popen. terminate() with subprocess.
Both kill or terminate are methods of the Popen object. On macOS and Linux, kill sends the signal signal. SIGKILL to the process and terminate sends signal. SIGTERM .
You can kill a child process using the Process. kill() or Process. terminate() methods.
Popen is more general than subprocess. call . Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With