from contextlib import contextmanager
@contextmanager
def run_and_terminate_process(*args, **kwargs):
try:
p = subprocess.Popen(*args, **kwargs)
yield p
finally:
p.terminate() # send sigterm, or ...
p.kill() # send sigkill
def main():
with run_and_terminate_process(args) as running_proc:
# Your code here, such as running_proc.stdout.readline()
import signal
import sys
import subprocess
import os
def signal_handler(signal, frame):
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
a = subprocess.check_output(["ls", "-l"], stderr=subprocess.STDOUT)
while 1:
pass # Press Ctrl-C (breaks the application and is catched by signal_handler()
proc = subprocess.Popen(["ls", "-l"], stdout=PIPE, stderr=PIPE)
# Here you can get the PID
global child_pid
child_pid = proc.pid
# Now we can wait for the child to complete
(output, error) = proc.communicate()
if error:
print "error:", error
print "output:", output
要确保在出口处杀死孩子:
import os
import signal
def kill_child():
if child_pid is None:
pass
else:
os.kill(child_pid, signal.SIGTERM)
import atexit
atexit.register(kill_child)
是的,你可以通过两种方法来实现。两者都要求您使用
Popen
,而不是check_output
。第一种是更简单的方法,使用try..最后,如下所示:这将捕获sigint(键盘中断)和sigterm,但不会捕获sigkill(如果使用-9终止脚本)。
另一种方法比较复杂,使用ctypes的prctl PR_SET_PDEATHSIG。一旦父进程因任何原因退出(甚至sigkill),系统将向子进程发送一个信号。
不知道具体细节,但最好的方法仍然是用信号捕捉错误(甚至可能是所有错误),并终止任何剩余的进程。
这只是一个模型,你需要捕捉的不仅仅是SIGINT,但这个想法可能会让你开始,你还需要检查生成的进程。
http://docs.python.org/2/library/os.html#os.killhttp://docs.python.org/2/library/subprocess.html#subprocess.Popen.pidhttp://docs.python.org/2/library/subprocess.html#subprocess.Popen.kill
我建议重写
check_output
的个性化版本,因为我刚刚意识到check_输出实际上只是为了简单的调试等,因为在执行过程中不能与它进行太多交互。。重写检查输出:
使用它做任何你想做的事情,也许将活动的执行存储在一个临时变量中,并在退出时用信号或其他方法隐藏主循环的错误/关闭来杀死它们。
最后,您仍然需要在主应用程序中捕获终止符,以便安全地杀死任何child,最好的方法是使用
try & except
或signal
。您的问题是使用
subprocess.check_output
-您是正确的,您无法使用该接口获取子PID。改为使用Popen:要确保在出口处杀死孩子:
相关问题 更多 >
编程相关推荐