Skip to content Skip to sidebar Skip to footer

Kill Subprocess When Python Process Is Killed?

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 ki

Solution 1:

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

Solution 2:

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.

Solution 3:

You can use python atexit module.

For example:

import atexit

def killSubprocess():
    mySubprocess.kill()

atexit.register(killSubprocess)

Post a Comment for "Kill Subprocess When Python Process Is Killed?"