使用子进程时如何在异常时向子进程发送终止信号

How to send terminate signal to the child process on exception, when using subprocess

我正在通过子进程从另一个 python 程序中 运行 宁一个 python 程序,我这样称呼它。

try:
    subproc = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, 
shell=True)
    o, e = subproc.communicate()
    sys.stdout.write(o)
    sys.stderr.write(e)
except:
    subproc.terminate()

在被调用的程序中,我注册了如下所示的信号处理程序。然而,尽管调用了 terminate 函数,但在上面的程序中,它永远不会在异常时被调用。但是,如果我单独 运行 子程序,则 handle_exit 函数可以正常调用。我在这里犯了什么错误?

def handle_exit(sig, frame):
    print('\nClean up code here)
    ....

signal.signal(signal.SIGTERM, handle_exit)
signal.signal(signal.SIGINT, handle_exit)

更新: 好的,我通过将 subproc.terminate 替换为以下内容来使其正常工作。

subproc.send_signal(signal.SIGINT)
subproc.wait()

这很好,但我还想在异常时获得子进程的输出。我怎样才能得到它?

我找到了解决方案,就在这里。

try:
    subproc = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, 
shell=True)
    o, e = subproc.communicate()
except:
    subproc.send_signal(signal.SIGINT)
    o, e = subproc.communicate()
sys.stdout.write(o)
sys.stderr.write(e)