How to run a script in Python as a Service - Caronte Consulting

How to run a script in Python as a Service

Here is a short guide on how to run a Python script when starting Linux

In this article, we will explain how to easily execute a Python script when Linux starts. In fact, inserting a script to service is very useful if we wanted to build a device (for example an RTU) that starts to capture data when the operating system starts. In addition, the service is extremely convenient to start or stop with a single command line.

The script, Start.sh and Stop.sh

Suppose that our Python script to be executed is located in the folder:

/home/pi/Script/MyScript.py

To this file we must add two more files: Start.sh and Stop.sh. The Start.sh file will serve to start the script, while the Stop.sh file will serve to stop the script. Let’s start creating the files by opening the terminal and typing:

touch Start.sh
sudo pico Start.sh

we insert the content:

#!/bin/bash
/usr/bin/python /home/pi/Script/MyScript.py

to save press CTRL + O, press Enter and then close with CTRL + X. We set the file permissions as follows:

chmod a+x Start.sh

Now let’s create the Stop.sh file as follows:

$ touch Stop.sh
$ sudo pico Stop.sh

we insert the content:

#!/bin/bash
for KILLPID in `ps ax | grep ‘MyScript’ | awk ‘{print $1;}’`; do
kill -9 $KILLPID;
done

save by pressing CTRL + O, press Enter and then close with CTRL + X. We set the file permissions as follows:

chmod a+x Stop.sh

As you can easily see, the code violently stops the script, instantly nipping its execution.

The script as a service

Now let’s create a service that launches the script when the operating system starts. Always from the terminal we run the following command:

sudo pico /etc/systemd/system/name_script.service

and insert the following content:

[Unit]
Description=NAME_SCRIPT service
After=network.target

[Service]
Type=simple
ExecStart=/bin/bash /home/pi/Script/Start.sh
ExecStop=/bin/bash /home/pi/Script/Stop.sh
Restart=always
RestartSec=5
TimeoutSec=60
RuntimeMaxSec=infinity
PIDFile=/tmp/nome_script.pid

[Install]
WantedBy=multi-user.target

don’t forget to change the name_script with a name associated with your script. Save by pressing CTRL + O, then press Enter and then close with CTRL + X. At this point we launch the last commands:

sudo systemctl enable /etc/systemd/system/name_script.service
sudo systemctl daemon-reload
sudo service name_script start

At this point your script will be put into service and will be started. To check for errors or not, you can run this command:

sudo service name_script status

To stop the script, you can run the command:

sudo service name_script stop

Find out more about our intelligent devices for Industry 5.0!

Our goal is to improve and make industrial processes safer thanks to intelligent devices customized on client’s needs.

Share your thoughts