There 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 :
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 :
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.
46 Comments
Perfect for running my IP detection script.
https://github.com/manuti/Check_IP_and_send_email
http://raspberryparatorpes.net
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 🙂
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!
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.
Thank you! I will try that.
The program starts at boot, and recognizes the GPIO signals, but when it plays audio files, no sound comes out of the speakers. Any ideas?
Make sure that the output is set to your needs:
sudo amixer cset numid=3 1
amixer cset numid=3 n where:
Where is the required interface : 0=auto, 1=analog, 2=hdmi.
cavok, That didn’t work for me. Where does the output from Python print commands go? It might help to see the output.
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
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?
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.
Neat! Thanks!
Would this also execute scripts that require sudo access ?
For e.g starting up a Flask server on start up …
Should work fine. I use it to launch Python scripts that use GPIO and they require sudo.
Very nice Tutorial
worked fine.
I needed
os.chdir(“myDirectory”)
in my python script file…
Thanks for this tip! Was wondering why my script for capturing videos on startup wasn’t working and I realized that I overlooked this because of your comment.
Worked perfectly! I’ve used this a couple of times now. Thank you!
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.
Thanks for this post.
It works.
Thanks John
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.
What image are you using and where are you getting it from?
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?
Add a blank file in the boot partition named “ssh”. Then use SSH to remotely connect to the Pi over a network. You can then edit the cron settings.
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!
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 * * * *”.
Hi great tutorial but I was wondering if I wanted the program to run over the startup (all of it) what would I do?
Thanks this worked perfectly for me. Running a python script at startup for a PIR Raspb Pi project
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
Are you definitely using sudo when calling “crontab-e”?
thank you! works great!
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!
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?
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.
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?
You would need to write the Python script so it included a loop. ie a “while” loop.
I tried your crontab idea, but when I reboot it asks for a login.
That may be the expected behavior depending on what you are expecting your script to do?
Hi,
I tried adding a cron job which opens a particular url in browser when invoked in python.
But the action didn happen when cron was executed. I get the results when I run from command line. Please help
Hi there, I followed the instructions, it seems to be working because I can see the pid but my py file has some output, ie, print. So how can I start the terminal and see the output? Thank you
This worked for me
I just had to remove my password so sudo would work.
http://www.raspberrypi.org/forums/viewtopic.php?f=29&t=7192
For those that are running python scripts at startup that have to be delayed a bit there is a small workaround possible. I had an issue with python script running @reboot but it ran before the peripherals were ready. So I modified the crontab from this:
@reboot /usr/bin/python /path/to/my/pythonscript.py
to
@reboot sleep 20 && /usr/bin/python /path/to/my/pythonscript.py
After that modification everything works like a charm.
Works like a charm that way.
I followed the steps and when I rebooted, it seemed that my python program was running (with the code I log sensordata to a textfile and a led blinks every 5 seconds). When i wanted to stop the program, i did the kill command like described.
Unfortunately, the script doesn’t stop. (led keeps blinking)
When I rebooted, my data wasn’t logged either, there was no .txt file.
How is it possible that the proces doesn’t stop whit the kill-command? Any solutions?
Unless you flush or close the file the data may be held in memory. So the process is probably getting killed before it has written any data to the file. At certain intervals you may need to use the Python “flush” and the “os.fsync” commands. I’m not sure why the kill command isn’t working. If the process disappears from the process list then it is no longer running. Are you sure you are killing the correct process?
cron worked GR8!
I recommend not using daemontools, etc/inittab, rc.local, rc, init.d or bash_profile.
Crontab works great, but be aware that it runs in the background and does not have a terminal attached to output to. I’d like to run a python script from pi crontab that outputs to a small PiTFT display as the default terminal. Has anyone found a workaround to print to a terminaL?
For scripts that need to output something using systemd is probably the better technique.