确保含有子进程的Python脚本在SIGINT上终止

2022-03-07 00:00:00 python signals

问题描述

我有一个命令,我将其包装在script中,并使用subprocess.Popen从Python脚本生成该命令。我正在尝试确保如果用户发出SIGINT

我可以确定进程是否至少以两种方式中断:

A.如果WRIPTED命令具有非零退出状态(不起作用,因为script似乎总是返回0),则退出

B.在父Python脚本中使用SIGINT做一些特殊的事情,而不是简单地中断子进程。我尝试了以下方法:

import sys
import signal
import subprocess

def interrupt_handler(signum, frame):
    print "While there is a 'script' subprocess alive, this handler won't executes"
    sys.exit(1)
signal.signal(signal.SIGINT, interrupt_handler)

for n in range( 10 ):
    print "Going to sleep for 2 second...Ctrl-C to exit the sleep cycles"

    # exit 1 if we make it to the end of our sleep
    cmd = [ 'script', '-q', '-c', "sleep 2 && (exit 1)", '/dev/null']
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    while True:
        if p.poll() != None :
            break
        else :
            pass

    # Exiting on non-zero exit status would suffice
    print "Exit status (script always exits zero, despite what happened to the wrapped command):", p.returncode

我想按Ctrl-C退出python脚本。实际上,子进程终止,脚本继续运行。


解决方案

此黑客可以工作,但很难看.

将命令更改为:

success_flag = '/tmp/success.flag'
cmd = [ 'script', '-q', '-c', "sleep 2 && touch " + success_flag, '/dev/null']

并将

if os.path.isfile( success_flag ) :
    os.remove( success_flag )
else :
    return

在for循环末尾

相关文章