HOW TO RUN A SCRIPT AS A SERVICE IN RASPBERRY PI – RASPBIAN JESSIE

HOW TO RUN A SCRIPT AS A SERVICE IN RASPBERRY PI – RASPBIAN JESSIE

  • Post author:
  • Post category:Linux / IOT

HOW TO RUN A SCRIPT AS A SERVICE IN RASPBERRY PI – RASPBIAN JESSIE: The Raspberry Pi is an incredible popular credit card size mini computer with awesome capabilities.  Despite of is mini size it behaves pretty much like a regular computer (it has an OS with a graphical interface, an ethernet port so you can surf the web, an HDMI output, etc.) but also it exposes several inputs/outputs (GPIO) to interact with the real world (sensors and cool tech gadgets).

A pretty common task when using this device, is to run some script (for example a python script) as a service in the operating system so it can start on boot, stop and restart using systemctl and more. In this post I’m going to explain how to set a little script as a service using Raspbian Jessie in a Raspberry Pi.

First of all, we are going to write a small python script which print “Hello World” every 60 seconds. This is going to be our service script (hello_world.py):

You can execute it by python hello_world.py. If you get boring reading so many hello worlds, press Ctrl+C (or Cmd+C on OSX) to stop it. Save this file as hello_world.py in your home folder (home/pi/). Now we’re going to define the service to run this script:

The service definition must be on the /lib/systemd/system folder. Our service is going to be called “hello.service”:

means is aborted is going to be restarted automatically. You can check more on service’s options in the next wiki: https://wiki.archlinux.org/index.php/systemd.

Now that we have our service we need to activate it:

For every change that we do on the /lib/systemd/system folder we need to execute a daemon-reload (third line of previous code). If we want to check the status of our service, you can execute:

In general:

REFERENCES

  1. https://wiki.archlinux.org/index.php/systemd
  2. https://www.digitalocean.com/community/tutorials/understanding-systemd-units-and-unit-files
  3. https://coreos.com/os/docs/latest/getting-started-with-systemd.html