【问题标题】:How to send terminate signal to the child process on exception, when using subprocess使用子进程时如何在异常时向子进程发送终止信号
【发布时间】: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()

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

【问题讨论】:

    标签: python linux signals


    【解决方案1】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 2019-06-20
      • 2013-07-30
      • 2022-06-15
      • 2011-01-21
      • 2019-04-11
      相关资源
      最近更新 更多