← Knowledge Base
PythonReference note1 min read · updated 2026-11-27

Run a Python script as a systemd service

A unit file for a long-running script, with a restart policy, its own user and logs in the journal.

pythonsystemdservice
# /etc/systemd/system/myscript.service
[Unit]
Description=My Python worker
After=network-online.target
Wants=network-online.target

[Service]
User=svc-worker
WorkingDirectory=/opt/myscript
ExecStart=/opt/myscript/.venv/bin/python worker.py
Restart=on-failure
RestartSec=5
Environment=PYTHONUNBUFFERED=1
EnvironmentFile=-/etc/myscript.env

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now myscript
journalctl -u myscript -f

Run it as a dedicated unprivileged user, point ExecStart at the virtual environment's interpreter and keep secrets in the environment file (mode 600, owned by root). PYTHONUNBUFFERED=1 makes print output appear in the journal immediately.