If you have a Python script that you need to run automatically, one great solution is to create a systemd service. This way lets you manage your script using the service
command just like any other daemon. Creating your own service on Debian 9 only requires creating one .service
file and registering it with systemd. Easy!
System service files are located in /lib/systemd/system/
. You can also create user services and those are stored in /usr/lib/systemd/system/
. These files specify all the details that systemd needs to start and control the services. There are a lot of options that can be included, however, in its most basic form we only need a few basic things. The example below shows the minimum requirements. Let’s say we put this in a new file at /lib/systemd/system/python-example.service
[Unit] Description=My Python Example Service After=default.target [Service] Type=simple ExecStart=/usr/bin/python /home/me/example.py Restart=on-abort [Install] WantedBy=default.target
To enable the service with systemd, simply tell systemd to enable it as shown below.
# Enable the new service we just created systemctl enable python-example.service # Manually start and check its status service python-example start service python-example status
That’s all you need to run a Python script as a service! At some point I may throw together an example script and add it to this article, but for now this should get you going.
Further Reading
- Creating Systemd Service Files https://www.devdungeon.com/content/creating-systemd-service-files
- FreeDesktop.org – systemd.service man page
https://www.freedesktop.org/software/systemd/man/systemd.service.html - How to write a systemd .service file running systemd-tmpfiles https://unix.stackexchange.com/questions/61390/how-to-write-a-systemd-service-file-running-systemd-tmpfiles