Running a Python Script on Boot with Systemd

This short blog post details how you can run a python script on boot using systemd.

Using Systemd to manage the python script

Systemd is a daemon that is used to control various aspects of services and initialization scripts that run on and after boot. It is used by a wide range of Linux systems and provides a simple interface to define services that it will launch on boot.

In this case I am going to use it to launch a python script when the Raspberry Pi boots, to turn on the scripts for the Raspberry Pi Cluster.

Creating the Service file

The service file should live under the folder /etc/systemd/system and should end in .service. My example file is:

/etc/systemd/system/raspberry-pi-cluster.service

[unit]
Description=Raspberry Pi Cluster
After=multi-user.target

[Service]
Type=idle
ExecStart=/usr/bin/python3 /home/pi/Documents/RaspberryPiCluster/basic_primary.py
User=pi

[Install]
WantedBy=multi-user.target

Here the description is used to help idetify what the service is doing.

ExecStart=/usr/bin/python3 /home/pi/Documents/RaspberryPiCluster/basic_primary.py

The ExecStart references the script that you want to run to start the service. It is recommended to use the full paths to all executables so they can be launched by the process which might not have the location in its path variable.

User=pi

In my case I also put the User field in the configuration so it will be launched as the pi user. By default it will launch as root.

Starting and enabling the service

Once your service file has been created you will need to enable and start the service.

systemctl daemon-reload
systemctl enable raspberry-pi-cluster.service
systemctl start raspberry-pi-cluster.service

Here the systemd settings are reloaded and your new service will be discovered. Once this is done we can enable the service (so it will run on startup) and then start it.

Once done the service will automatically run on boot.

If you have any further questions as to how to do this, feel free to drop a comment below. If this worked or you have any suggested tweaks I would love to know too!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.