开发者

kill subprocess when python process is killed?

开发者 https://www.devze.com 2022-12-08 22:32 出处:网络
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

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 inter开发者_如何学编程rupt to try something else.

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


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


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.


You can use python atexit module.

For example:

import atexit

def killSubprocess():
    mySubprocess.kill()

atexit.register(killSubprocess)
0

精彩评论

暂无评论...
验证码 换一张
取 消