我在函数中有一些耗时的任务,我希望即使在主进程退出后也能运行该函数。
代码示例:
def do_time_consuming_thing():
// do time consuming task here
time.sleep(30)
def worker():
print "start a child process:"
p = multiprocessing.Process(target=do_time_consuming_thing,args=())
p.start()
print "child pid:%d" % p.pid
sys.exit(0) // main process exit here.
def test():
worker()
但是当我在shell命令行中运行上述代码时,在子进程完成之前,我无法返回命令行提示符。
如何在 sys.exit(0( 完成后立即返回命令行提示符。
在你的代码中替换你的退出线
sys.exit(0)
有了这个:
os._exit(0)
来自 python 文档:
os._exit(n(
以状态 n 退出进程,而不调用清理处理程序、刷新 stdio 缓冲区等。
我不能说我推荐这种方法,但如果要求使用多处理模块,它回答了你的问题。
尝试在p.start()
之前设置p.daemon = True
。看这里。