捕获 Ctrl-C 信号并等待子进程 [英] Capture Ctrl-C Signal And Wait For Subprocess

查看:50
本文介绍了捕获 Ctrl-C 信号并等待子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些 python 代码,我在其中调用了一个子进程,在 python 脚本中,我想捕获 SIGINT 信号,并等待子进程完成.目前,当我按 ctrl-c 时,我所拥有的会杀死进程.有什么方法可以告诉 python 等待进程完成?虽然我想等待该过程,但我确实希望该脚本在该过程完成后死亡,不确定是否有办法做到这一点.

I have a bit of python code in which I call a subprocess, and within the python script I want to capture the SIGINT signal, and wait for the subprocess to finish. Currently what I have kills the process when I ctrl-c. Any way to tell python to wait for the process to finish? Although I want to wait for the process, I do want the script to die after the process finishes, not sure if theres a way to do this.

import subprocess as sp  
from celery.platforms import signals 

def outer_fun(): 
    p = None

    def signal_handler(signum, frame): 
        if p != None: 
            p.wait()

signals['INT'] = signal_handler 

p = sp.Popen(['sleep','30'])
result = p.wait() 

print result[0]

outer_fun()

推荐答案

找到了一个解决方案,虽然不是我预期的效果!使用 preexec_fn=os.setpgrp 选项,ctrl c 信号不会发送到子进程.

Found a solution, although not what I expected it works! With the preexec_fn=os.setpgrp option the ctrl c signal is not sent to the subprocess.

p = sp.Popen(cmd, preexec_fn=os.setpgrp)

这篇关于捕获 Ctrl-C 信号并等待子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆