In this lesson, you will learn how to transform your robust Python automation scripts into production-grade background daemons using systemd.
When you build long-running automation—like a file watcher or a resource monitor—manual execution is insufficient. You need your script to start on boot, restart automatically if it crashes, and log its output consistently. In the Linux ecosystem, systemd is the standard for managing these persistent background processes.
Creating the Service Unit
To deploy your script, you must define a "unit file" (e.g., my_automation.service) located in /etc/systemd/system/. This file tells the OS exactly how to handle your process:
[Unit]
Description=My Python Automation Service
After=network.target
[Service]
ExecStart=/usr/bin/python3 /path/to/your/script.py
WorkingDirectory=/path/to/your/app
Restart=always
User=automation_user
Environment=APP_ENV=production
[Install]
WantedBy=multi-user.target
Key Considerations for Daemons
- High Availability: By setting
Restart=always,systemdmonitors the process. If your script encounters an unhandled exception or a system crash, the service manager will automatically relaunch it, ensuring your automation remains continuous. - Proper Logging: When running as a system service, standard
printstatements are redirected to the system journal. You can view these logs instantly usingjournalctl -u my_automation.service -f. This fulfills our requirement for robust logging, as it centralizes your script's output without you needing to manage external log files manually. - Graceful Termination: Since you have already learned how to handle system signals (SIGTERM/SIGINT), ensure your Python script listens for these signals. When you run
systemctl stop my_automation,systemdsends a signal to your process; if your script is built to catch these, it can close database connections or finish current tasks before shutting down, preventing data corruption.
Once configured, enable your service with systemctl enable my_automation so it starts every time the server reboots. This simple configuration layer elevates your script from a developer tool to a reliable production component.
Key Takeaway: By wrapping your Python automation in a systemd unit file, you guarantee persistent operation, automated recovery, and centralized logging via the system journal.