Python - 如何在提前退出时重新启动子进程?
Python - How to restart a child process on early exit?
假设我有一个应用程序需要永远 运行 子进程,并且只会在出现错误时退出。 (比如说进程被命名为 Q1 和 Q2)。
Q1 和 Q2 应该永远 运行。但是,它们可能会因错误而终止。在这种情况下,主进程应该只重新启动终止的进程。
我怎样才能找到任何终止的进程并重新启动它们,而不发生任何阻塞?
其他参考资料1.
你可以这样做:
from multiprocessing import Pool
from time import sleep
def foo():
print("foo here")
sleep(3)
raise Exception
def bar():
print("bar here")
while True:
sleep(5)
print("'bar'-process still alive")
if __name__ == "__main__":
restarts = foo, bar
results = {func: None for func in restarts}
with Pool(processes=2) as p:
while True:
for func in restarts:
results[func] = p.apply_async(func)
print(f"'{func.__name__}'-process (re)started")
sleep(1)
restarts = (
func
for func, result in results.items()
if result.ready() and not result.successful()
)
假设我有一个应用程序需要永远 运行 子进程,并且只会在出现错误时退出。 (比如说进程被命名为 Q1 和 Q2)。
Q1 和 Q2 应该永远 运行。但是,它们可能会因错误而终止。在这种情况下,主进程应该只重新启动终止的进程。
我怎样才能找到任何终止的进程并重新启动它们,而不发生任何阻塞?
其他参考资料1.
你可以这样做:
from multiprocessing import Pool
from time import sleep
def foo():
print("foo here")
sleep(3)
raise Exception
def bar():
print("bar here")
while True:
sleep(5)
print("'bar'-process still alive")
if __name__ == "__main__":
restarts = foo, bar
results = {func: None for func in restarts}
with Pool(processes=2) as p:
while True:
for func in restarts:
results[func] = p.apply_async(func)
print(f"'{func.__name__}'-process (re)started")
sleep(1)
restarts = (
func
for func, result in results.items()
if result.ready() and not result.successful()
)