【发布时间】:2019-07-07 16:01:07
【问题描述】:
我正在通过子进程从另一个 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()
在被调用的程序中,我注册了如下所示的信号处理程序。但是,尽管调用了终止函数,但在上述程序中,它永远不会被异常调用。但是如果我单独运行子程序,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()
这很好,但我也想在异常时获得子进程的输出。我怎样才能得到它?
【问题讨论】: