Making sure a Python script with subprocesses dies on SIGINT(确保含有子进程的Python脚本在SIGINT上终止)
本文介绍了确保含有子进程的Python脚本在SIGINT上终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个命令,我将其包装在script
中,并使用subprocess.Popen
从Python脚本生成该命令。我正在尝试确保如果用户发出SIGINT
。
我可以确定进程是否至少以两种方式中断:
A.如果WRIPTED命令具有非零退出状态(不起作用,因为script
似乎总是返回0),则退出
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上终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:确保含有子进程的Python脚本在SIGINT上终止
基础教程推荐
猜你喜欢
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01