首页 > 编程语言 > 详细

python to be linux daemon

时间:2015-11-10 19:14:05      阅读:303      评论:0      收藏:0      [点我收藏+]

所需第三方库:python-daemon[https://pypi.python.org/pypi/python-daemon/]

使用方式:

  python linux_service.py start/stop/restart

from mythings import start
from daemon import runner
import os
import logging
import inspect

class App:

    def __init__(self):
        self.stdin_path = /dev/null
        self.stdout_path = /dev/tty
        self.stderr_path = /dev/tty
        self.pidfile_path = /tmp/foo.pid
        self.pidfile_timeout = 5
        self.status = {alive: True}
        this_file = inspect.getfile(inspect.currentframe())
        current_path = os.path.abspath(os.path.dirname(this_file))
        self.logfile = os.path.join(current_path, service.log)

    def _getLogger(self):
        logger = logging.getLogger([My Service])
        logger.setLevel(logging.DEBUG)
        fh = logging.FileHandler(self.logfile)
        fh.setLevel(logging.DEBUG)
        #ch = logging.StreamHandler()
        #ch.setLevel(logging.DEBUG)
        formatter = logging.Formatter(%(asctime)s %(name)-12s %(levelname)-8s %(message)s)
        fh.setFormatter(formatter)
        #ch.setFormatter(formatter)
        logger.addHandler(fh)
        #logger.addHandler(ch)
        logger.info(init logger...)
        return logger

    def run(self):
        self.logger = self._getLogger()
        self.logger.info(linux svc do run...)
        start(self.status, self.logger)


app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()

备注:

日志级别:UNSET < DEBUG < INFO < WARNNING < ERROR<CRITICAL

ch.setLevel(logging.DEBUG)时,可以打印出级别大于等于DEBUG的日志(包括DEBUG,INFO ,WARNNING , ERROR,CRITICAL)

python to be linux daemon

原文:http://www.cnblogs.com/flowjacky/p/4953758.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!