python ------Daemon实现

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python ------Daemon实现相关的知识,希望对你有一定的参考价值。

上一篇python ------Daemon 守护进程学习了python 守护进程类的实现,这一篇实现了一个时间提醒的类timereminder继承Daemon。

 计时器类:

技术分享
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import threading

class Timer(threading.Thread):  
        """ 
        very simple but useless timer. 
        """  
        def __init__(self, seconds):  
                self.runTime = seconds  
                threading.Thread.__init__(self)  
        def run(self):  
                time.sleep(self.runTime)  
                print "Buzzzz!! Time‘s up!"  
  
class CountDownTimer(Timer):  
        """ 
        a timer that can counts down the seconds. 
        """  
        def run(self):  
                counter = self.runTime  
                for sec in range(self.runTime):  
                        time.sleep(1.0)  
                        counter -= 1  
  
class CountDownExec(CountDownTimer):  
        """ 
        a timer that execute an action at the end of the timer run. 
        """  
        def __init__(self, seconds, action, args=[]):  
                self.args = args  
                self.action = action  
                CountDownTimer.__init__(self, seconds)  
        def run(self):  
                CountDownTimer.run(self)  
                self.action(self.args)  
  
def myAction(args=[]):  
        print "Performing my action with args:"  
        print args  

if __name__ == "__main__":  
        t = CountDownExec(3, myAction, ["hello", "world"])  
        t.start() 
View Code

消息提醒脚本:

技术分享
#!/usr/bin/env python
import threading
import time
import sys

id = 0

class listener(threading.Thread):
    def __init__(self,strs=()):
        threading.Thread.__init__(self)
        self.strs= strs
    def run(self):
        global id 
        while not (id in self.strs):
            input = raw_input(need to have a free time now!(y|n)\\n)
            id = input

listen = listener((y,Y))
listen.setDaemon(True)
listen.start()
counter =10
while not (id in (y,Y)):
    time.sleep(1)
    print (need to hava a free time now!(y|n)) 
    if id in(n,N):
        counter = 30 # remind 30 times
    counter = counter -1
    if counter < 0:
        id = y
View Code

提醒类(timereminder):

技术分享
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys,time,subprocess,os
from mod_daemon import Daemon
from mod_timer import CountDownExec

class TimeReminder(Daemon):
    def __init__(self,limittime,pidfile,stderr,stdout,stdin):
        Daemon.__init__(self,pidfile,stderr,stdout,stdin)
        self.limittime = limittime

    def logout(self,str):
        logfile = open(self.stdout,a)
        currenttime = time.asctime(time.localtime(time.time()))
        logfile.write("begin %s at %s \\n" % (str,currenttime))
        logfile.flush()
        logfile.close()
    
    def run(self):
        self.logout(start this program)
        while True:
            t= CountDownExec(self.limittime,presentresult,["hello","world"])
            t.start()            
            t.join()
            self.logout(remind to relax)

def presentresult(args=[]):
    cmd="xterm -e ./sandbox/py_time_reminder/out.py"  # present reminder
    child=subprocess.Popen(cmd,shell=True)
    child.wait()
            
def getlimittime():
    try:
        pros = open(/sandbox/py_time_reminder/pros.ini,r)
        timepro = int(pros.read().strip())
        pros.close()
    except:
        sys.exit(must set time property first)
    if timepro:
        return timepro
    else:
        return int(20)

def setlimittime(tim):
    pros = open(/sandbox/py_time_reminder/pros.ini,w)
    pros.write("%s\\n" %tim)
    pros.close()

if __name__ == "__main__":
    if len(sys.argv)<2:
        sys.exit(No action specified.)
    else:
        if sys.argv[1].startswith(--):
            option = sys.argv[1][2:]
            if option == limit and len(sys.argv) == 3:
                mytimelimit = sys.argv[2]
                setlimittime(mytimelimit)
            elif option == version:
                print ‘‘‘version   : 1.1
author    : victor‘‘‘
            elif option == help:
                print ‘‘‘This program is to remind to have a free time after set-time work.
option includes:
    --help     : display this help
    --limit    : set [time](s) to remind
    --version  : diaplay version details
usage includes:
    start      : program start
    stop       : program stop
    restart    : program restart ‘‘‘
            else:
                print Unkown option.
            sys.exit(0)
        elif len(sys.argv) == 2:
            ltime= getlimittime()
            daemon = TimeReminder(ltime,/sandbox/py_time_reminder/daemon.pid,stderr=/sandbox/py_time_reminder/daemonerr.log, stdout=/sandbox/py_time_reminder/daemonout.log, stdin=/dev/null)
            if start == sys.argv[1]:
                daemon.start()
            elif stop == sys.argv[1]:
                daemon.stop()
            elif restart == sys.argv[1]:
                daemon.restart()
            else:
                print("Unkown command")
            sys.exit(0)
        else:        
            print ("usage: %s --help" % sys.argv[0])
            sys.exit(2)    
View Code

 

以上是关于python ------Daemon实现的主要内容,如果未能解决你的问题,请参考以下文章

Python开发

Python 介绍

Python学习之认识python

python初识

Python 线程池模块,Python 多线程

如何切换python版本