捕获Ctrl-C信号并等待子进程

时间:2023-01-11 04:00:54

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.

我有一些python代码,我在其中调用子进程,并在python脚本中我想捕获SIGINT信号,并等待子进程完成。目前我在ctrl-c时杀死了这个过程。有什么办法告诉python等待进程完成?虽然我想等待这个过程,但我确实希望脚本在进程完成后死掉,不确定是否有办法执行此操作。

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

1 个解决方案

#1


0  

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.

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

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

#1


0  

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.

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

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