退出主进程

时间:2017-08-04 02:32:33

标签: python python-2.7 multiprocessing

我在一个函数中有一些耗时的任务,我希望这个函数在主进程退出后运行。

代码示例:

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)完成后立即返回命令行提示符。

2 个答案:

答案 0 :(得分:1)

尝试在p.daemon = True之前设置p.start()。请参阅here

答案 1 :(得分:0)

在您的代码中替换您的退出行

sys.exit(0)

用这个:

os._exit(0)

来自python docs:

  

os._exit(n)的

     

退出状态为n的进程,不调用清理处理程序,刷新stdio缓冲区等。

我不能说我推荐这种方法,但如果需要使用多处理模块,它会回答你的问题。

相关问题