Programming Raspberry Pi

Run Python On Your Raspberry Pi As background Service

There are many ways to run a python program as a background service on your raspberry pi at startup. We will use the systemd method.

  • Create a .service file for your service as below:
 sudo nano /lib/systemd/system/helloworld.service
  • Add the below text:
 [Unit]
Description=Hello World Service
After=multi-user.target

[Service]
Type=idle
ExecStart=/usr/bin/python /home/pi/helloworld.py
User=pi

[Install]
WantedBy=multi-user.target
  • Save and exit the nano editor (by pressing Ctrl+X).
  • The permission on the unit file needs to be set to 644 :
 sudo chmod 644 /lib/systemd/system/helloworld.service
  • Reload the system manager configuration by using the following command:
 sudo systemctl daemon-reload
  • Start the service using the following command:
 sudo systemctl start helloworld.service
  • Stop the service using the following command:
 sudo systemctl stop helloworld.service
  • You can enable the service to start at boot as below:
 sudo systemctl enable helloworld.service
Please follow and like us:
Ganga
Ganga is a Developer and Application Architect with a passion for programming and cooking.

Leave a Reply

Your email address will not be published. Required fields are marked *