一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

python如何设置守护进程 python设置守护进程代码示例

时间:2020-10-29 编辑:袖梨 来源:一聚教程网

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 没有启动便随着主进程的结束而结束。

热门栏目