Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill a running subprocess call

I'm launching a program with subprocess on Python.

In some cases the program may freeze. This is out of my control. The only thing I can do from the command line it is launched from is CtrlEsc which kills the program quickly.

Is there any way to emulate this with subprocess? I am using subprocess.Popen(cmd, shell=True) to launch the program.

like image 886
Thomas O Avatar asked May 31 '13 21:05

Thomas O


People also ask

How do you kill a subprocess call?

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 .

How do you kill a process in Python?

A process can be killed by calling the Process. kill() function. The call will only terminate the target process, not child processes.

Does subprocess call wait for completion?

The subprocess module provides a function named call. This function allows you to call another program, wait for the command to complete and then return the return code.

How do I close OS Popen in Python?

This function is intended for low-level I/O and must be applied to a file descriptor as returned by os. open() or pipe() . To close a “file object” returned by the built-in function open() or by popen() or fdopen() , use its close() method.


2 Answers

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 subprocess
import time

process = 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 subprocess
import time
import os
import signal

process = subprocess.Popen(cmd, shell=True)
time.sleep(5)
os.kill(process.pid, signal.SIGINT)
like image 166
Aya Avatar answered Sep 23 '22 17:09

Aya


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

like image 43
butch Avatar answered Sep 22 '22 17:09

butch