Python守护进程用法实例分析

WBOY
Release: 2016-06-06 11:18:09
Original
1145 people have browsed it

本文实例讲述了Python守护进程用法。分享给大家供大家参考。具体分析如下:

守护进程是可以一直运行而不阻塞主程序退出。要标志一个守护进程,可以将Process实例的daemon属性设置为True。代码如下:

import os
import time
import random
import sys
from multiprocessing import Process,current_process
def daemon():
    p = current_process()
    print "starting ID%d prccess%s\n" % (p.pid,p.name)
    sys.stdout.flush()
    time.sleep(3)
    print "Exiting:%s\n" % p.name
    sys.stdout.flush()
def main():
    p = Process(name="Daemon",target=daemon)
    p.daemon=True
    p.start()
if __name__=="__main__":
    main()
    time.sleep(1)

Copy after login

由于主进程会在1秒后退出,守护进程的 print  "Exiting:%s\n" % p.name这句是看不到的。

若想看到守护进程的 print  "Exiting:%s\n" % p.name语句输出,可以利用join,主进程等待守护进程的退出后再退出,即在,p.start()后添加p.join()然后把time。sleep(1)删除

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template