Using Systemd and SDNotify to Manage your Python Daemons

Talha Khaild
3 min readNov 30, 2024

I’m not going to go into a long intro, Systemd being the de facto service supervisor for the most important Linux distros, it quickly becomes interesting to learn its little-known features to take full advantage of its platform without having to install anything.

Photo by Mohammad Rahmani on Unsplash

I often have to create daemons to query all types of databases or remote systems. I generally use Python for these tasks, which allows me to set up what I have in mind very quickly. To overcome the ‘amateur’ effect of the thing, I therefore use systemd which will manage the services reliably, at least more reliably than a simple nohup ;)

Starting from a useless script for the following example:

from time import sleep

## Here will be my procedure for connecting to the database or
# any other remote service to contact first
try:
while True:
print('Hello world!')
sleep(5)
except KeyboardInterrupt:
print('Exiting...')
finally:
# Here will be the shutdown functions for my open connections above
pass

How to make this piece of code more robust? Using Systemd will already be a good step forward :)

The sdnotify library

Systemd provides notification methods between the system layer and the started program. This is to let the…

--

--