Python Daemonize Library

2.5.0 · active · verified Thu Apr 16

daemonize is a Python library designed to allow your code to run as a well-behaved daemon process on Unix-like systems. It simplifies the complex steps involved in daemonization, such as forking, session management, and PID file handling. The current version is 2.5.0, and it is actively maintained with releases occurring periodically, typically a few times a year or every couple of years.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a simple daemon that logs messages every 5 seconds. It correctly handles logging by keeping the log file's file descriptor open across the daemonization process. The `pid` argument specifies the PID file path, `action` is the function to run as a daemon, and `keep_fds` ensures necessary file descriptors remain open.

import time
import os
import logging
from daemonize import Daemonize

# Configure logging BEFORE daemonization if you want it to persist
# The log file descriptor needs to be passed to keep_fds
log_file = "/tmp/test_daemon.log"
pid_file = "/tmp/test_daemon.pid"

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.propagate = False
fh = logging.FileHandler(log_file, "w")
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)

keep_fds = [fh.stream.fileno()]

def main():
    count = 0
    while True:
        logger.info(f"Daemon is running. Count: {count}")
        count += 1
        time.sleep(5)

if __name__ == "__main__":
    # Ensure the PID directory exists
    os.makedirs(os.path.dirname(pid_file), exist_ok=True)

    # Initialize Daemonize object
    daemon = Daemonize(
        app="test_app", 
        pid=pid_file, 
        action=main, 
        keep_fds=keep_fds, 
        chdir="/", 
        verbose=True # Set to False for production
    )

    # Start the daemon. For debugging, you can call main() directly
    # to run in foreground: main()
    logger.info(f"Starting daemon '{daemon.app}' with PID file '{daemon.pid}'")
    daemon.start()

view raw JSON →