python如何设置守护进程 python设置守护进程代码示例
python如何设置守护进程?本篇文章小编给大家分享一下python设置守护进程代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
我们通过两个例子说明
# encoding: utf-8 """ author: yangyi@youzan.com time: 2019/7/30 11:20 AM func: """ from multiprocessing import Process import os import time def now(): return str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) def func_1(name): print(now() + ' Run child process %s ,pid is %s...' % (name, os.getpid())) time.sleep(2) print(now() + ' Stop child process %s ,pid is %s...' % (name, os.getpid())) def func_2(name): print(now() + ' Run child process %s , pid is %s...' % (name, os.getpid())) time.sleep(4) print(now() + ' hello world!') print(now() + ' Stop child process %s , pid is %s...' % (name, os.getpid())) if __name__ == '__main__': print ('Parent process %s.' % os.getpid()) p1 = Process(target=func_1, args=('func_1',)) p2 = Process(target=func_2, args=('func_2',)) print now() + ' Process start.' p1.daemon = True #设置子进程p1为守护线程 p1.start() p2.start() print now() + ' Process end .'
结果显示
启动了子进程 Run child process func_1 但是没有 func_1 的结束提示。随着主进程的结束而结束。
if __name__ == '__main__': print ('Parent process %s.' % os.getpid()) p1 = Process(target=func_1, args=('func_1',)) p2 = Process(target=func_2, args=('func_2',)) print now() + ' Process start.' p2.daemon = True #设置子进程p2为守护线程 p1.start() p2.start() print now() + ' Process end .'
结果显示
启动了子进程func_1,而func_2 没有启动便随着主进程的结束而结束。
-
上一篇: Java如何实现宠物商店管理 Java实现宠物商店管理代码示例
-
下一篇: TypeScript魔法堂之枚举的超实用代码原理解析
PHP之友评论