python如何在分离模式下运行进程

编程入门 行业动态 更新时间:2024-10-10 04:24:19
本文介绍了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如何在分离模式下运行进程

本文发布于:2023-11-16 02:17:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1600098.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:进程   如何在   模式下   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!