{"id":7122,"library":"daemonize","title":"Python Daemonize Library","description":"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.","status":"active","version":"2.5.0","language":"en","source_language":"en","source_url":"https://github.com/thesharp/daemonize","tags":["daemon","process","unix","background"],"install":[{"cmd":"pip install daemonize","lang":"bash","label":"Install stable version from PyPI"}],"dependencies":[],"imports":[{"symbol":"Daemonize","correct":"from daemonize import Daemonize"}],"quickstart":{"code":"import time\nimport os\nimport logging\nfrom daemonize import Daemonize\n\n# Configure logging BEFORE daemonization if you want it to persist\n# The log file descriptor needs to be passed to keep_fds\nlog_file = \"/tmp/test_daemon.log\"\npid_file = \"/tmp/test_daemon.pid\"\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nlogger.propagate = False\nfh = logging.FileHandler(log_file, \"w\")\nfh.setLevel(logging.DEBUG)\nlogger.addHandler(fh)\n\nkeep_fds = [fh.stream.fileno()]\n\ndef main():\n    count = 0\n    while True:\n        logger.info(f\"Daemon is running. Count: {count}\")\n        count += 1\n        time.sleep(5)\n\nif __name__ == \"__main__\":\n    # Ensure the PID directory exists\n    os.makedirs(os.path.dirname(pid_file), exist_ok=True)\n\n    # Initialize Daemonize object\n    daemon = Daemonize(\n        app=\"test_app\", \n        pid=pid_file, \n        action=main, \n        keep_fds=keep_fds, \n        chdir=\"/\", \n        verbose=True # Set to False for production\n    )\n\n    # Start the daemon. For debugging, you can call main() directly\n    # to run in foreground: main()\n    logger.info(f\"Starting daemon '{daemon.app}' with PID file '{daemon.pid}'\")\n    daemon.start()\n","lang":"python","description":"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."},"warnings":[{"fix":"Identify all necessary open file descriptors (e.g., `logger.handlers[0].stream.fileno()` for a file handler) and pass them as a list to the `keep_fds` parameter.","message":"File descriptors (like log file handles, sockets) are typically closed during daemonization. If you want them to remain open and functional in the daemon process, you MUST explicitly pass their file descriptors to the `keep_fds` argument of the `Daemonize` constructor.","severity":"gotcha","affected_versions":"All versions"},{"fix":"For cross-platform daemon-like behavior, consider alternative approaches like using separate process management tools (e.g., systemd on Linux, Windows Services) or libraries specifically designed for multi-platform background processes, if strict daemonization isn't required.","message":"The `daemonize` library is designed exclusively for Unix-like operating systems (Linux, macOS, etc.) and will not function on Windows. Attempting to use it on Windows will result in errors related to missing POSIX functions (e.g., `os.fork`).","severity":"breaking","affected_versions":"All versions"},{"fix":"Create the directory if it doesn't exist using `os.makedirs(os.path.dirname(pid_file), exist_ok=True)` and verify file system permissions. If dropping privileges (`user`, `group`), ensure the target user has write access to the PID file location.","message":"Ensure the directory for the PID file (`pid` argument) exists and that the user the daemon runs as has write permissions to it. If not, the daemonization process will fail with a `Permission denied` error or similar.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Ensure the library is installed using `pip install daemonize` and that you are running your script in the correct Python environment (e.g., a virtual environment).","cause":"The `daemonize` package is not installed or the Python environment where it's installed is not active.","error":"ImportError: No module named daemonize"},{"fix":"Pass the file descriptors of your log files (e.g., `logging.FileHandler.stream.fileno()`) or other critical I/O resources to the `keep_fds` argument when initializing `Daemonize`.","cause":"During daemonization, the operating system closes all inherited file descriptors by default. If your logging setup (or any other I/O) relies on an open file descriptor that wasn't explicitly preserved, it will cease to function or cause the daemon to crash.","error":"The daemon starts, but no logs appear after the initial startup messages, or the daemon process silently exits."},{"fix":"Ensure the directory containing the PID file (`/path/to/`) exists and is writable by the user account under which the daemon is intended to run. If dropping privileges with `user` or `group` parameters, ensure those specific users/groups have write access.","cause":"The user attempting to run the daemon, or the user that the daemon process switches to, does not have write permissions to create or update the specified PID file.","error":"OSError: [Errno 13] Permission denied: '/path/to/daemon.pid'"}]}