Creating a Python System Service

I came across the need to run a python script every time my Pi restarted. It is a pretty simple process, you can use this for more than just python but that is my specific use case. Pick a unique name for your service and fill it into the command below replacing service_name.

sudo nano /etc/systemd/system/service_name.service

We are now editing the new file with nano. If it is not a new file and not empty try another service name its already in use. If you want to run the script as a specific user you can use the following:

[Unit]
Description=my python daemon
After=network.target

[Service]
User=username_here
Group=group_name_here
WorkingDirectory=/path/to/script/folder
ExecStart=python3 script_name.py

[Install]
WantedBy=multi-user.target

Pretty simple? There is another option if you want to run the script from the system level we can remove the User and Group lines. Please note if you run from a system level you need to install any packages you may need using pip3 with sudo pip3 instead.

So we have a service, now let’s start it, check it, and make it run at boot. First to start our service:

sudo systemctl start service_name

Let’s check that everything went ok:

sudo systemctl status service_name

Finally, if we want it to run after every boot we need to enable it with the following command:

sudo systemctl enable service_name

That’s it, you now have a service that will start every time your pi does.

By Andrew

I love technology, and when I found Raspberry Pi's I was instantly hooked. Within the first week I had at least 5. I am also a avoid programmer so I made this blog about my creations to help others do cool things with their Pi's.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x