python-systemd-daemon-example.md
Create a program in python
Example: x.py
prints out increasingly large random numbers, once per second:
import math
from random import randint
from time import sleep
t = 0
while True:
x = randint(0,100) + t
y = ((x * math.pi) / (x * math.e + (math.e/10))) * x
t += 1
print(f"TIME: {t}, X: {x}")
sleep(1)
Create service definition
sudo vim /lib/systemd/system/xpy.service
The example below hands off logging to journalctl, saving output to /var/log/daemon.log
(or syslog
). Output is unbuffered (-u
).
[Unit]
Description=XPY Service
After=multi-user.target
Conflicts=getty@tty1.service
[Service]
Type=simple
ExecStart=/usr/bin/python3 -u /root/x.py
StandardOutput=journal
StandardError=inherit
StandardInput=tty-force
Restart=on-failure
[Install]
WantedBy=multi-user.target
Enable and start the service
sudo systemctl daemon-reload
sudo systemctl enable xpy.service
sudo systemctl start xpy.service
Monitor the service's logs
sudo tail -f /var/log/daemon.log
- OR:
sudo tail -f /var/log/syslog.log
Example output:
python3[1761667]: TIME: 1, X: 57
python3[1761667]: TIME: 2, X: 70
python3[1761667]: TIME: 3, X: 62
python3[1761667]: TIME: 4, X: 4
python3[1761667]: TIME: 5, X: 34
python3[1761667]: TIME: 6, X: 30
python3[1761667]: TIME: 7, X: 19
python3[1761667]: TIME: 8, X: 22
python3[1761667]: TIME: 9, X: 42
python3[1761667]: TIME: 10, X: 27
python3[1761667]: TIME: 11, X: 101
python3[1761667]: TIME: 12, X: 71
[...]
NOTES
- You can send a SIGKILL signal to the service and it will restart automatically:
sudo systemctl --signal=SIGKILL kill <servicename>