Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a subprocess called using subprocess.call in python? [duplicate]

Tags:

python

I am calling a command using

subprocess.call(cmd, shell=True)

The command won't terminate automatically. How to kill it?

like image 375
rubyman Avatar asked Jul 13 '16 19:07

rubyman


People also ask

How do you end a subprocess call in Python?

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.

How do I kill a process launched by Popen?

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 .

How do you kill a process in Python?

You can kill a child process using the Process. kill() or Process. terminate() methods.

What is the difference between subprocess call and Popen?

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.


1 Answers

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

like image 103
mgilson Avatar answered Oct 11 '22 14:10

mgilson