6

I am writing a python program that lauches a subprocess (using Popen). I am reading stdout of the subprocess, doing some filtering, and writing to stdout of main process.

When I kill the main process (cntl-C) the subprocess keeps running. How do I kill the subprocess too? The subprocess is likey to run a long time.

Context: I'm launching only one subprocess at a time, I'm filtering its stdout. The user might decide to interrupt to try something else.

I'm new to python and I'm using windows, so please be gentle.

3 Answers3

5

Windows doesn't have signals, so you can't use the signal module. However, you can still catch the KeyboardInterrupt exception when Ctrl-C is pressed.

Something like this should get you going:

import subprocess

try:
    child = subprocess.Popen(blah)
    child.wait() 

except KeyboardInterrupt:
    child.terminate()
  • 2
    A warning from the python documentation on Popen.wait(): Warning This will deadlock if the child process generates enough output to a stdout or stderr pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use communicate() to avoid that. – pythonic metaphor Oct 21 '09 at 21:55
  • 1
    Actually `signal.signal(signal.SIGINT, handlerFunc)` works just fine on Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32; I just tried it. – RobM Jul 08 '10 at 12:12
0

subprocess.Popen objects come with a kill and a terminate method (differs in which signal you send to the process).

signal.signal allows you install signal handlers, in which you can call the child's kill method.

pythonic metaphor
  • 10,296
  • 18
  • 68
  • 110
0

You can use python atexit module.

For example:

import atexit

def killSubprocess():
    mySubprocess.kill()

atexit.register(killSubprocess)
Maksym Ganenko
  • 1,288
  • 15
  • 11