我在一个函数中有一些耗时的任务,并且我希望该函数即使在主进程退出后也能运行。
代码示例:
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)
Exit the process with status n, without calling cleanup handlers, flushing stdio buffers, etc.
我不能说我推荐这种方法,但如果要求是使用多处理模块,它可以回答您的问题。
关于python - 为什么 python 脚本在主进程退出后挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45497386/