使用子流程时

时间:2019-07-07 16:01:07

标签: python linux signals

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

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

那很好,但我也想获取异常时子进程的输出。我该怎么办?

1 个答案:

答案 0 :(得分:0)

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

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)