确保子进程在退出Python程序时失效 [英] Ensuring subprocesses are dead on exiting Python program
问题描述
有没有办法确保所有创建的子进程在Python程序退出时都消失了?所谓子流程,是指那些用subprocess.Popen()创建的内容.
Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen().
如果不是,我是否应该遍历所有发出的终止点,然后终止-9?还有更清洁的东西吗?
If not, should I iterate over all of the issuing kills and then kills -9? anything cleaner?
推荐答案
您可以使用 为此,请atexit ,并注册程序退出时要运行的所有清理任务.
You can use atexit for this, and register any clean up tasks to be run when your program exits.
atexit.register(func [,* args [,** kargs]])
在清理过程中,您还可以实现自己的等待,并在发生所需的超时时将其终止.
In your cleanup process, you can also implement your own wait, and kill it when a your desired timeout occurs.
>>> import atexit
>>> import sys
>>> import time
>>>
>>>
>>>
>>> def cleanup():
... timeout_sec = 5
... for p in all_processes: # list of your processes
... p_sec = 0
... for second in range(timeout_sec):
... if p.poll() == None:
... time.sleep(1)
... p_sec += 1
... if p_sec >= timeout_sec:
... p.kill() # supported from python 2.6
... print 'cleaned up!'
...
>>>
>>> atexit.register(cleanup)
>>>
>>> sys.exit()
cleaned up!
注意-如果该进程(父进程)被杀死,将不会运行注册的功能.
Note -- Registered functions won't be run if this process (parent process) is killed.
python> = 2.6不再需要以下Windows方法
这是一种杀死Windows中进程的方法.您的Popen对象具有pid属性,因此您可以通过 success = win_kill(p.pid)来调用它(需要 pywin32 已安装):
Here's a way to kill a process in windows. Your Popen object has a pid attribute, so you can just call it by success = win_kill(p.pid) (Needs pywin32 installed):
def win_kill(pid):
'''kill a process by specified PID in windows'''
import win32api
import win32con
hProc = None
try:
hProc = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, pid)
win32api.TerminateProcess(hProc, 0)
except Exception:
return False
finally:
if hProc != None:
hProc.Close()
return True
这篇关于确保子进程在退出Python程序时失效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!