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?

标签: python, daemon

仅有一条评论

  1. 上述代码在Python 3.6下报错:

    gf@guofengdeMacBook-Pro /p/tmp> ./test.py start
    Traceback (most recent call last):
    File "./test.py", line 36, in
    daemon_runner = runner.DaemonRunner(app)
    File "/usr/local/miniconda3/lib/python3.6/site-packages/daemon/runner.py", line 120, in __init__
    app.stderr_path, 'w+t', buffering=0)
    ValueError: can't have unbuffered text I/O

添加新评论