Running A Python Script At Boot Using Cron

Python LogoThere maybe times when you want to run a Python script when your Raspberry Pi boots up. There are a number of different techniques to do this but I prefer the method that uses “cron”.

Cron is a job scheduler that allows the system to perform tasks at defined times or intervals. It is a very powerful tool and useful in lots of situations. You can use it to run commands or in this case, a Python script.

Step 1 – Create A Python Script

The first step is creating your Python script. This will be the script that will run at boot time. It is important to remember its name and location. In this example I will assume the script is called “MyScript.py” and it is located in “/home/pi/”.

Double check you’ve got the correct path by typing :

cat /home/pi/MyScript.py

This should show the contents of your script.

Make sure your script works and does what you expect it to. Once you are running at boot it isn’t so easy to debug so don’t rush!

Step 2 – Add A New Cron Job

To create a new job to Cron we will modify the “crontab”. This is a table that contains the list of jobs that Cron will monitor and run according to it’s details. To edit it we use the command :

sudo crontab -e

Each user of the system (ie “pi”) can have its own Crontab but in this case we want to add it as an admin so we prefix our “crontab -e” command with “sudo”. You should see something that looks like this :

Crontab Example - Python at Boot

Using your cursor keys scroll to the bottom and add the following line :

@reboot python /home/pi/MyScript.py &

This tells Cron that every boot (or reboot or start-up) we want to run Python with the script MyScript.py. The “&” at the end of the line means the command is run in the background and it won’t stop the system booting up as before.

Your screen should look something like this :

Crontab Example - Python at Boot

To save these changes click “CTRL-X”, then “Y” and finally “Return”. You should now be back at the command prompt.

To start testing you can now reboot using :

sudo reboot

Once setup your Python script will run whenever your reboot or start-up your Pi. There may be times when you reboot and don’t want the script running. To stop it you can find out its process number and “kill” it. To do this type :

ps aux | grep /home/pi/MyScript.py

This should give you a line starting with “root” and ending in the path to your script. Immediately after the “root” should be a process number. For example :

root  1863  0.0  1.0  24908  4012 ?  Sl  19:45  0:00  python  /home/pi/MyScript.py

In this case we can stop the process using :

sudo kill 1863

Final Thoughts

If you are feeling adventurous you can write your Python script to automatically exit if a certain condition is met so you don’t need to ever “kill” it. Ideas include :

  • Test the GPIO pins and quit if a switch is being pressed. Maybe two switches being held down.
  • Test if a network connection is available and quit if it is. This may indicate you are testing (a camera for example) and you only want the script to auto-run when there is no network present.
  • Check for the existence of a particular file. This would allow you to create a named file to prevent the script from running at next boot.

There are other techniques to run scripts at boot up and you might want to Google “rc.local” or “init.d”. I prefer the Cron method because it is so simple.

For additional information on the powerful features of Cron take a look at the Wikipedia Cron page.

This entry was posted in Python, Raspbian and tagged , . Bookmark the permalink.



33 Responses to Running A Python Script At Boot Using Cron

  1. J Ashfield says:

    Thanks for this post, I spent most of this morning looking a easy way to do this. It’s sooo easy your way, I tried testing other methods but they were too hard for a newbie like me. I thoroughly enjoy reading your posts. My favorite project is the 20×4 LCD ,I bought one and used it to display the temperature from the digital thermometer (the one from your post) and got it to run the program at startup :)

  2. JimT says:

    I have a python program that plays wav files depending on GPIO pin readings. It works fine when I run it from the command line, but it doesn’t appear to work when I start it using Cron. I see it running when I issue the ‘ps aux’ command, but there is no audio when I start it using Cron. Another odd thing is that ‘sudo kill’ does not kill that process.

    I have to run it using ‘sudo’ from the command line, but ‘ps aux’ shows that it runs as root when I put it in Cron, so I don’t think that’s the problem.

    Any ideas on how I can debug this? Thank you!

  3. cavok says:

    i also had a similar problem,
    exact same issue as described above. depending on which method the script was autostarted it would work or not…
    python script playing wav file depending on interrupt on the gpio state.
    here’s what worked for me:

    1. make a file “/bin/autologin.sh”

    2. put the following two lines in it:
    #!/bin/bash
    /bin/login -f root

    3. set permissions
    chmod a+x /bin/autologin.sh

    4. edit “/etc/inittab”
    find a line that looks very similar and edit it to:
    1:2345:respawn:/sbin/getty -n -l /bin/autologin.sh 38400 tty1

    5. edit “/root/.bashrc”
    add the following 3 lines:
    if [[ $(tty) == ‘/dev/tty1′ ]]; then
    python /home/pi/yourscript.py
    fi

    and it should reliably start at every boot.

  4. JimT says:

    cavok, That didn’t work for me. Where does the output from Python print commands go? It might help to see the output.

  5. Shane says:

    Having a similar problem
    Have my RPi receiving inputs from an MPR121 and either triggering an arduino via serial to make patterns with an LED strip, or play sounds using py game mixer.
    If I run from the command line (I have just put the file in /home/pi/beetbox_serial.py) run as sudo then all is well.
    If I schedule it (cron or /etc/rc.local to try it at startup) then I get serial output (and so lights) but no sounds- just a pop (also no printout from the Python script which I do get (tells me which inputs are triggered) when this works

    Is this an Env setting problem? Is this something due to the GPIO? The GPIO’s are reading it’s the sound output that is the problem (seems common to this thread)

    Any help would be appreciated

    Shane

  6. carlos says:

    Hi, I did as you explained, my script is just

    print “hello”

    print “hello”
    print “hello”
    print “hello”

    I removed the & at the end of the crontab statements, but nothing happens. Do you have any idea why this is happening?

    • Matt says:

      It is possible it is running but you won’t see the output because it happens before you’ve logged in. If your script was flashing an LED in a loop it would be easier to see. I use this technique to launch scripts that read sensors and take photos so the script keeps running in a loop in the background.

  7. zarafiq says:

    Neat! Thanks!

  8. Mohit says:

    Would this also execute scripts that require sudo access ?
    For e.g starting up a Flask server on start up …

  9. Rrusporoxus says:

    Very nice Tutorial
    worked fine.

    I needed
    os.chdir(“myDirectory”)
    in my python script file…

  10. Shawn says:

    Worked perfectly! I’ve used this a couple of times now. Thank you!

  11. Maham says:

    Don’t know why, it is not working for me :( . I have followde the above instructions carefully.

    1. I made a python script “Hello.py” in /home/pi
    2. I checked,if it running or not,it is giving me output.
    3. I used crontab -e command and added the line @reboot python /home/pi/Hello.py &
    4. Reboot RPi using sudo reboot , but nothing happened!

    Please help me out.

  12. John Streff says:

    Thanks for this post.
    It works.
    Thanks John

  13. bill says:

    I can not edit the file. I actually can’t edit any of the files people suggest I edit to make a script run at start.

    There is always a permission problem. How can I get around it? I use a fresh installation every time I try.

    There must be some way to bypass this whole “permissions” thing altogether as it truly serves no purpose.

    I need to run a script at startup.

  14. Alex says:

    I did this with a python script of mine and now it boots to a black screen after the initial pi boot screen and then there is nothing I can do. Is there anyway to tell it to stop doing this without being able to startup properly? Anything through the cmdline.txt on the sd card? Or anyway to tell it not to run cron before it finishes booting and goes black?

  15. John says:

    Hi! I was using this example with one small Python code I was writing the other day and it works perfectly!

    By the way, what are the pros/cons of using this method instead of running your python code as a daemon on start up? Except from the complexity point of view!

  16. vali says:

    Nice ideea to expose here.

    With cron you can do more
    http://escapequotes.net/scheduling-tasks-with-cron/

    @reboot – Run once, at startup.
    @yearly – Run once a year, “0 0 1 1 *”.
    @annually – (same as @yearly)
    @monthly – Run once a month, “0 0 1 * *”.
    @weekly – Run once a week, “0 0 * * 0″.
    @daily – Run once a day, “0 0 * * *”.
    @midnight – (same as @daily)
    @hourly – Run once an hour, “0 * * * *”.

  17. Jim says:

    Hi great tutorial but I was wondering if I wanted the program to run over the startup (all of it) what would I do?

  18. sweenes says:

    Thanks this worked perfectly for me. Running a python script at startup for a PIR Raspb Pi project

  19. Mike says:

    Hi, I’m coding for an RFID project I am doing and wanted to run my python script on boot. For some reason it isn’t running at all and instead of running in root it’s using pi instead. Does anyone know why?

    Thanks

  20. craig says:

    thank you! works great!

  21. Owen says:

    Dude. Thank you so much. I’ve read so many other guides to this and they were either ridic complex or straight up didn’t work. This was like a 20 second job and it works perfectly. Thanks mate. Hugely appreciated!

  22. Chris Jordan says:

    I’m pretty sure using @reboot in the crontab only runs the command when you actually reboot the PI (i.e. run sudo reboot), if you simply pull the power and plug it back in, it doesn’t run.

    This error caused me to have a cold shower after a power cut (my PI runs my heating).

    This seems like an odd behaviour I know, but I tested it a few times. I wonder why cron doesn’t have an @startup too?

    • Matt says:

      Strange. It definitely works for me. I’ve used it on a few projects and it runs when the Pi is powered up from cold.

  23. sara rahmati says:

    thank you it works great.what if i want a program to run forever?for example i have a python script that the pi camera wait for pressing a button and after that capture an image .what if i want the program run always and the picamera wait for pressing what time i want?

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>