python - 为什么 python 脚本在主进程退出后挂起

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

最佳答案

在您的代码中替换退出行

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/

相关文章:

python - 发送到python3中程序的标准输入

python - "Import Error: dynamic module does not define init function (init_mysql)"在 OS X 上导入 MySQLdb

python - 使用 os.kill 将 SIGINT 发送到 Python 子进程,就像按 Ctrl+C 一样

multithreading - 为什么hadoop任务的实时时间明显大于用户+系统时间?

python - 多处理调试技术

python - 如何简化数组提取值

python - 如何更新 Django 中的查询集值?

python - 如何查看 Tkinter 中是否存在小部件?

python - numpy.memmap 映射保存文件

python - pip 要求说明符 : role of the comma