{"library":"python-daemon","code":"import daemon\nimport time\nimport logging\nimport sys\nimport os\n\n# Optional: for robust PID file management\ntry:\n    from lockfile import pidlockfile\nexcept ImportError:\n    pidlockfile = None\n\nLOG_FILE = '/tmp/my_daemon.log'\nPID_FILE = '/tmp/my_daemon.pid'\n\ndef do_program_work():\n    logging.basicConfig(\n        filename=LOG_FILE,\n        level=logging.INFO,\n        format='%(asctime)s - %(levelname)s - %(message)s'\n    )\n    logger = logging.getLogger()\n    logger.info(\"Daemon started.\")\n\n    # Example: Keep track of open log file descriptor\n    # so daemon does not close it.\n    log_handler_file = None\n    for handler in logger.handlers:\n        if hasattr(handler, 'stream') and hasattr(handler.stream, 'fileno'):\n            log_handler_file = handler.stream.fileno()\n            break\n\n    while True:\n        logger.info(f\"Daemon still running at {time.ctime()}\")\n        time.sleep(5)\n\n\nif __name__ == '__main__':\n    # Prepare a PID file object if lockfile is installed\n    pid_file = None\n    if pidlockfile:\n        pid_file = pidlockfile.TimeoutPIDLockFile(PID_FILE)\n\n    # Open the daemon context\n    # Explicitly keep stdout/stderr for debugging, typically redirect to /dev/null or log file\n    with daemon.DaemonContext(\n        working_directory='/',\n        umask=0o002, # Set umask explicitly; 0o022 or 0o027 are common\n        pidfile=pid_file,\n        stdout=sys.stdout, # For demonstration, usually redirect to a log file or /dev/null\n        stderr=sys.stderr, # For demonstration, usually redirect to a log file or /dev/null\n        files_preserve=[log_handler_file] if log_handler_file else [] # Preserve log file descriptor\n    ):\n        do_program_work()\n","lang":"python","description":"This quickstart demonstrates how to use `DaemonContext` as a context manager to daemonize a simple Python script. It includes basic logging, optional PID file management using `lockfile.pidlockfile.TimeoutPIDLockFile`, and important configurations like `working_directory`, `umask`, and preserving open file descriptors for logging. Run this script and observe that it detaches from the terminal and continues to run, logging to `/tmp/my_daemon.log`.","tag":null,"tag_description":null,"last_tested":"2026-04-24","results":[{"runtime":"python:3.10-alpine","exit_code":1},{"runtime":"python:3.10-slim","exit_code":1},{"runtime":"python:3.11-alpine","exit_code":1},{"runtime":"python:3.11-slim","exit_code":1},{"runtime":"python:3.12-alpine","exit_code":1},{"runtime":"python:3.12-slim","exit_code":1},{"runtime":"python:3.13-alpine","exit_code":1},{"runtime":"python:3.13-slim","exit_code":1},{"runtime":"python:3.9-alpine","exit_code":1},{"runtime":"python:3.9-slim","exit_code":1}]}