zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python守护进程 - python-daemon

Python进程 守护 daemon
2023-06-13 09:16:16 时间

python的守护进程模块,遵循PEP 3143,很好很强大!

install

# https://pypi.python.org/pypi/python-daemon/
sudo pip install python-daemon

Usage

import logging
import time

# third party libs
from daemon import runner


class Updater():
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path = '/tmp/testdaemon.pid'
        self.pidfile_timeout = 5

    def run(self):
        while True:
            # Main code goes here ...
            # Note that logger level needs to be set to logging.DEBUG before this shows up in the logs
            logger.debug("Debug message")
            logger.info("Info message")
            logger.warn("Warning message")
            logger.error("Error message")
            time.sleep(10)


app = Updater()
logger = logging.getLogger("DaemonLog")
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler = logging.FileHandler("/tmp/testdaemon.log")
handler.setFormatter(formatter)
logger.addHandler(handler)

daemon_runner = runner.DaemonRunner(app)

# This ensures that the logger file handle does not get closed during daemonization
daemon_runner.daemon_context.files_preserve = [handler.stream]
daemon_runner.do_action()

Refer:

Create a daemon on Ubuntu Building a python daemon process How do you use python-daemon the way that it's documentation dictates?