确保含有子进程的Python脚本在SIGINT上终止 [英] Making sure a Python script with subprocesses dies on SIGINT

查看:40
本文介绍了确保含有子进程的Python脚本在SIGINT上终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个命令,我将其包装在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循环末尾

这篇关于确保含有子进程的Python脚本在SIGINT上终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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