Running a Python Script as a Linux Systemd Service
To run a Python script continuously in the background on a Linux system, you can register it as a systemd service. This approach ensures automatic startup on boot and recovery after unexpected termination.
Prerequisites
Ensure you have a working Python script. For this example, assume the script is located at /home/username/scripts/app.py.
Step-by-Step Setup
1. Prepare the Python Script
Verify that your script runs correctly from the command line:
python3 /home/username/scripts/app.py
2. Create a Systemd Unit File
Create a new service file under /etc/systemd/system/, for instance app.service:
sudo nano /etc/systemd/system/app.service
3. Configure the Service Definition
Populate the file with the following content:
[Unit]
Description=Background service for app.py
After=network.target
[Service]
Type=simple
User=username
Group=username
WorkingDirectory=/home/username/scripts
ExecStart=/usr/bin/python3 /home/username/scripts/app.py
Restart=on-failure
RestartSec=5
Environment=PATH=/home/username/venv/bin:/usr/bin
[Install]
WantedBy=multi-user.target
Key directives explained:
After=network.target: Delays startup until networking is available.WorkingDirectory: Sets the base directory for relative paths.ExecStart: Full command to launch the script.Restart=on-failure: Restarts only if the process exits abnormally.Environment: Ensures the correct Python binary and virtual environment are used.
Note: If using a virtual environment, replace
/usr/bin/python3inExecStartwith the full path to the interpreter inside the venv (e.g.,/home/username/venv/bin/python).
4. Reload Systemd Configuration
Notify systemd of the new service:
sudo systemctl daemon-reload
5. Enable and Start the Service
Activate the service immediately and configure it to start at boot:
sudo systemctl enable --now app.service
6. Verify Service Status
Check whether the service is active and running:
systemctl status app.service
7. Inspect Runtime Logs
View real-time or historical logs using journalctl:
journalctl -u app.service -f
This method provides a robust way to manage long-running Python applications as native Linux services with minimal overhead.