AutoRun your Python Code on Raspberry Pi – using Crontab

AutoRun your Python Code on Raspberry Pi – using Crontab

Unlike Arduino, the Raspberry Pi won’t run the code until it is executed manually. We need a scheduler to run the python code when the Pi is powered up or rebooted. Crontab (cron table) is scheduler used in Linux to schedule a specific task at a specific time. It is mostly used by Linux system Administrators to automate his daily tasks like scheduling backups and deleting old files, etc., Here we will be using it to launch the code during the startup, so we will be creating a shell script to navigate to the python code first and then launch it during startup using crontab.

Step 1:

First, create a ‘blink’ folder and then create an empty ‘blink.py’ file. It should be inside the path /home/pi/blink. (The /home/pi/ is the default user files path).

1Autorun Python code in RPi

Python code: blink.py

 

2Autorun Python code in RPi

 

Circuit Diagram:

Autorun Blink_bb

Step 2:

Open the terminal and navigate to the ‘blink’ folder by using the following command

 

Create a launcher script by typing the command in the terminal.

 

6 Autorun Python Code on Startup

Now the editor will get launched. Copy and paste the following code to the editor. This shell script will navigate to the blink code.

 

7 Autorun Python Code on Startup

 

Now press Ctrl – X and the press Y to Save. It will ask for filename leave it as ‘launcher.sh’ itself and press enter.

 

Step 3:

We want to make this launcher.sh script executable. Type the following command for it.

 

8 Autorun Pi

You can test the launcher script by typing the following command if you want to test.

Step 4:

Create a log directory for capturing logs incase of any errors. Navigate back to home directory and create a log directory there.

Step 5:

We need to schedule the launcher script to run during startup itself. Open the crontab by using the command.

 

11 Autorun Pi

Once the crontab window opens add this line at the end of the file.

 

12 Autorun Python with crontab

This will run the launcher script during startup. Now reboot the Pi and check the python code runs automatically. Connect the LED according to the circuit and you will see the LED blinking (blink.py runs) automatically when the Pi is powered up.

You can modify the file path and file name to run a python program during startup. The crontab can also be used to run a specific program at a specific time or every 10 minutes like that.

Share this post

Leave a Reply

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