python如何以分离模式运行进程

python how to run process in detached mode(python如何以分离模式运行进程)
本文介绍了python如何以分离模式运行进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

这是一个例子:

from multiprocessing import Process
import time


def func():
    print('sub process is running')
    time.sleep(5)
    print('sub process finished')


if __name__ == '__main__':
    p = Process(target=func)
    p.start()
    print('done')

我希望主进程在启动子进程后立即终止.但是在打印出完成"之后,终端仍在等待......有没有办法做到这一点,以便主进程在打印出完成"后立即退出,而不是等待子进程?我在这里很困惑,因为我没有调用 p.join()

what I expect is that the main process will terminate right after it start a subprocess. But after printing out 'done', the terminal is still waiting....Is there any way to do this so that the main process will exit right after printing out 'done', instead of waiting for subprocess? I'm confused here because I'm not calling p.join()

推荐答案

如果存在非守护进程.

通过在start()调用前设置daemon属性,可以使进程成为守护进程.

By setting, daemon attribute before start() call, you can make the process daemonic.

p = Process(target=func)
p.daemon = True  # <-----
p.start()
print('done')

注意:不会打印sub process finished消息;因为主进程将在退出时终止子进程.这可能不是你想要的.

NOTE: There will be no sub process finished message printed; because the main process will terminate sub-process at exit. This may not be what you want.

你应该做双叉:

import os
import time
from multiprocessing import Process


def func():
    if os.fork() != 0:  # <--
        return          # <--
    print('sub process is running')
    time.sleep(5)
    print('sub process finished')


if __name__ == '__main__':
    p = Process(target=func)
    p.start()
    p.join()
    print('done')

这篇关于python如何以分离模式运行进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

build conda package from local python package(从本地 python 包构建 conda 包)
How can I see all packages that depend on a certain package with PIP?(如何使用 PIP 查看依赖于某个包的所有包?)
How to organize multiple python files into a single module without it behaving like a package?(如何将多个 python 文件组织到一个模块中而不像一个包一样?)
Check if requirements are up to date(检查要求是否是最新的)
How to upload new versions of project to PyPI with twine?(如何使用 twine 将新版本的项目上传到 PyPI?)
Why #egg=foo when pip-installing from git repo(为什么从 git repo 进行 pip 安装时 #egg=foo)