Launch a Python script when starting your Raspberry Pi

Launch a Python script when starting your Raspberry Pi

There are many projects where, to work, you had to run a Python script. For example for a control station, a Jukebox with RFID chip, or a security alarm system.

The problem is that it is quite annoying to have to launch it by hand each time the Raspberry Pi starts… Because that means always having a keyboard, a mouse and a screen plugged in, or logging in by SSH to launch it.

One solution is to start the Python script as soon as the Raspberry Pi boots up, and we’ll see how to do that in this article.

Don’t know what a raspberry pi is? check this link.

Create a shell script

In the user folder, you have to create a shell file that will contain the commands to run to launch the Python script.

cd /home/pi
nano launch.sh

Code explanation:

The first line “cd /home/pi” allows you to move into your user directory.

The command “nano launch.sh” will create the file “launch.sh” and will open the nano text editor so that we can write in the file.

In the file, write the commands to run your Python script:

cd /home/pi/my-program
python3 my-program.py

Save the file by pressing ”Ctrl + X”, confirm by pressing “O” and validate you choice by pressing Enter.

Make the file executable

Before you can use this shell file, you have to make it executable:

chmod 755 launch.sh

Test your file and check that your python script is launched with the command:

sh launch.sh

If everything works, you can move on to the next step.

Create a log file

In your user directory, create a “logs” folder which will contain the various log files of your programs. They will be used to have a written trace in you have an error in your program.

mkdir /home/pi/logs

Add your file to crontab

crontab is a process for running scripts in the background. It will execute scripts and commands at specific times or during specific events.

To add a new command in crontab:

sudo crontab -e

At the bottom of the file, add the line:

@reboot sh /home/pi/launch.sh > /home/pi/logs/log.txt 2>&1

This line will allow you executing the command “sh /home/pi/launch.sh” when starting the Raspberry Pi, and will save error messages and logs in the file “/home/pi/logs/log.txt ”.

Save with the shortcut “Ctrl + X“.

Check that everything is working

Reboot your Raspberry Pi:

reboot

If your program did not launch or there is a problem, check the log file to see if any errors have occurred.

That’s the end of this tutorial, I hope that tutorial could help you!

Write a comment below and tell us what will you use this script for?

Leave a Reply

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