我正在从另一个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)

10-08 07:54