Running Python Programs at boot on a Raspberry Pi

Running Python Programs at boot on a Raspberry Pi

When using the Raspberry Pi, many times you may have a program you want to automatically start it at boot so that you can use your project without logging in to the RaspberryPi via SSH or VNC.  Unlike the Arduino, the Pi needs to be set up to run a program automatically.

This tutorial will demonstrate how to auto-run Python programs on the Raspberry Pi, especially at startup.

Running programs automatically can help in robotics project where you want the robot to automatically start doing something or responding to commands as soon as the Raspberry Pi turns on.

One of the easiest ways of doing this is to use crontab.

Crontab is a table used by cron which is a daemon which is used to run specific commands at a particular time.  Crontab is very flexible: you can use Crontab to run a program at boot or to repeat a task or program at 12 PM every Wednesday.

To use crontab with your Raspberry Pi to automate your programs, follow these steps:

  1. Write your program and note down its location. We’ll be using a program called and save it at /home/pi/Desktop/pyprogSave the file and note the location
  2. Now open crontab.  You may need to open crontab in root (add sudo before the command!).
    crontab -e

    Open crontab

  3. Add a new entry at the very bottom with @reboot to specify that you want to run the command at boot, followed by the command. Here we want to run the python program and save the output in log.txt, so our entry is 

    @reboot sudo python /home/pi/Desktop/pyprog/

    Open crontab

  4. Now save the file and exit.Add the entry for reboot
  5. When you restart the pi, the command will be run and we will get the output log file.Program run and log createdBe a bit careful with the permissions and making sure that your program runs properly before you put it on boot: you can waste a lot of time trying to figure out what went wrong!
  6. Having trouble?  Check your bootlog:
grep cron /var/log/syslog

Got a question?  Need some help?  Ask away on our forums!

Learn More!

If you liked this tutorial, consider getting the Raspberry Pi here and SD Card with Raspbian for Robots here.