Kill a running subprocess call

80,795

Solution 1

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

Solution 2

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)
Share:
80,795
Thomas O
Author by

Thomas O

Student, Ubuntu 10.04 User. Uses Windows XP sometimes. Hates Vista with a passion. Interested in Windows 7, though haven't tried it much. Programs PIC microcontrollers in C and assembly. Favours dsPICs at the moment, but hasn't tried any other microcontroller yet. Prefers Python any day!

Updated on July 09, 2022

Comments

  • Thomas O
    Thomas O almost 2 years

    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.