当python进程被杀死时杀死子进程? [英] kill subprocess when python process is killed?

查看:98
本文介绍了当python进程被杀死时杀死子进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个启动子进程的 python 程序(使用 Popen).我正在读取子进程的标准输出,进行一些过滤,并写入主进程的标准输出.

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.

当我杀死主进程 (cntl-C) 时,子进程继续运行.我如何杀死子进程?子进程很可能运行很长时间.

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.

我是 Python 新手,我使用的是 Windows,所以请保持温和.

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

推荐答案

Windows 没有信号,所以你不能使用信号模块.但是,您仍然可以在按下 Ctrl-C 时捕获 KeyboardInterrupt 异常.

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

这篇关于当python进程被杀死时杀死子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆