Introduction: Raspberry Pi: Launch Python Script on Startup

As I've been working on my own Pi projects, I've been discovering many little tricks and tips by scouring various websites and assembling information, testing and optimizing.

So, here is another one of my "meat-and-potatoes" Raspberry Pi Instructables.

This Instructable will show you how to setup your Raspberry Pi to automatically launch a Python script upon startup.

First of all, I know this is a lame picture. If you can come up with a better one, I'm open to suggestions.

The Arduino has auto-launch built into it; the Pi does not. This will make your Pi a more powerful electronics platform and is essential if, for example, you want to use your Pi as a video kiosk using GPIO controls.

Before doing this Instructable, please make sure you have your Raspberry Pi up and running, which you can do with The Ultimate Raspberry Pi Configuration Guide Instructable.

I'm using the Mac OS for this guide, but you can extend the principles to other operating systems.

Step 1: Make a Launcher Sript

I'm building out a new project called Black Box Timelapse (Instructable coming soon...).

My python script is called : bbt.py and lives in a directory called bbt that is in the root directory. You can substitute your own director/Python script name instead of using mine.

We will use the Linux crontab to run the Python script.

I've had trouble with crontab and directory management and my solution is to amke a shell script, which always navigates to the proper directory and will launch my bbt.py Python script. 

Let's create the shell script!

I'm using ssh to access to Raspberry Pi. My IP address for the SD card for this is 10.0.1.68. Your IP address may be different — just change the address accordingly.

Open the Terminal window and on the command line, type:
ssh pi@10.0.1.68

If you are running directly hooked into the monitor, you can skip this step.

Type in:
cd bbt
then:
nano launcher.sh
Will launch your editor, type in this script

#!/bin/sh
# launcher.sh
# navigate to home directory, then to this directory, then execute python script, then back home

cd /
cd home/pi/bbt
sudo python bbt.py
cd /

Cntl-X, Return to save.

What this script will do is to navigate to the root directory, then to the bbt directory, launch the Python script and then return to the root directory.

Step 2: Make It Executable

We need to make the launcher script an executable, which we do with this command
chmod 755 launcher.sh
Now test it, by typing in:
sh launcher.sh
This should run your Python code.

Step 3: Add Logs Directory

We will get to using crontab in a minute, but first we need to make a directory for the any errors in crontab to go.

Navigate back to your home directory:
cd
Create a logs directory:
mkdir logs

Step 4: Add to Your Crontab

crontab is a background (daemon) process that lets you execute scripts at specific times. It's essential to Python and Raspberry Pi. The details are confusing, as is often the case with Linux. Once I got the hang of the format, I've found it to be incredibly easy to use.

Here's the Linux reference and here are some more crontab examples.

Type in:
sudo crontab -e
This will brings up a crontab window.

Now, enter the line:
@reboot sh /home/pi/bbt/launcher.sh >/home/pi/logs/cronlog 2>&1
What this does is rather than executing the launcher script at a specific time, it will execute it once upon startup.

Step 5: Reboot and See If It Works

Unplug the power or just type in:
sudo reboot
Wait for startup and see if your script automatically launches.

If it doesn't work, check out the log file:
cd logs
cat cronlog
This will show you any errors that you might have.

Step 6: Always Make an Exit Plan!

You'll want to have an easy way to exit the code, so that you don't get stuck in an endless buggy loop.

The way I do this is to plug in the keyboard (not plugged in for standard kiosk usage) and exit the script this way.

In a standard Python script, you can always hit cntl-C, which will exit.

If using the pygame libraries, you can do an exit on keydown, such as:
while not done:
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            done = True

Step 7: Extra: Crontab for Timed Scripts

Another way you can use crontab is to execute scripts at specific times, such as every minute, every hour, at a specific time. This is especially helpful for projects such as Twitterbots, which I'm using for my Bot Collective project

In this case, you want to make sure your Python script exits and isn't stuck in a loop, otherwise you may end up launching the script multiple times.

Here are some examples, with the same bbt.py/launcher code:

# every 2 minutes
*/2 * * * * /home/pi/justdiedbot/launcher.sh >/home/pi/logs/cronlog.log 2>&1

# at 6:22 EST, 3:22 PST (we are on PST); 15:22
22 15 * * * /home/pi/marktwainbot/launcher.sh >/home/pi/logs/cronlog.log 2>&1


Step 8: Done!

I hope this was helpful!
Scott Kildall

For more on Raspberry Pi code and other projects, you can find me here:
@kildall or www.kildall.com/blog

Comments

author
Bogdi_NSR (author)2017-08-22

Thanks for the guide. It's working just fine. I am running a bot for discord. However it boots and works just fine and everything but there is no terminal popping while it's on. The bot uses feedback on the terminal.

author
NidhiP15 (author)2017-08-21

I am trying to do similar experiment but I am stuck at one place, my python script has one statement in which I am untarring a big tar file (2.8G after untar). I have kept this python script in my crontab -e, so when I reboot and login to the machine, I see that tar command is still going on. I was assuming that when we give any script to crontab -e, it will complete full execution of the script and then only show linux logged in prompt. Can you please help me with this?

author
ParkerR11 (author)2017-08-09

HELP! I did this and now I have a black screen on boot! What do I do?

author
GabrielB164 made it! (author)2017-07-06

It has worked for me! I had to add the line

/bin/sleep 20

because I wanted my raspberry pi to first get connected to the wireless as my program requires it.

WhatsApp Image 2017-07-07 at 12.54.25 PM.jpeg
author
LeonardoA114 (author)2017-06-22

Good evening, I'm following the tutorial, but when I test launcher.sh I have the following error:

Traceback (most recent call last):
File "test.py", line 3, in
Import pygame
ImportError: No module named pygame


I'm using "import pygame" in my python script, do I need to do anything else for launcher.sh to recognize pygame?

author
YashS121 (author)LeonardoA1142017-07-01

Hey,

Is your python code working when you use it directly, I mean on shell?

Try it first "sudo python test.py "

If you get the same error then there is a problem with your script. look out if there is any because module import can be done on this launcher.sh script.

Let me know if it works or if you have any doubt.

Cheers!

author
TriRpi (author)2015-12-24

What does the "755" after chmod do. I know the 7 stands for: read, write, execute and the 5 for: read, execute. But why do you need three of those numbers and not 1?

author
daemoncan (author)TriRpi2017-05-16

When using the numeric method of assigning permissions in Unix/Linux, the values are in octal. So, you have three "masks" for each file's permissions. Owner, group, & everyone else. Like so:


OwnGrpOth

421421421

rwxrwxrwx

You add up the values for each permission granted for owner, group, & other. Typically for a script you'd want the owner to have read, write, & execute access, while granting only read & execute access to the group & other users.

Owner (4+2+1) = 7

Group & Other (4+1) = 5 (twice)

chmod 755 filename

HTH.

author
TannerB1 (author)TriRpi2016-01-23

The 7 is the permissions for the Owner, First 5 is the permissions for the Group assigned and second 5 is the permissions for the every other user on the system.

One number will be the equivalent of 777 so anyone can read, write,execute.

For more info, open the terminal and enter "man chmod" it will show you the manual page for how to use chmod

author
wellsey1972 (author)2017-02-23

I am tryin to run a camera Python program with a GUI and i get an error:

"no display name and no $DISPLAY environment variable"

Can you help me?

author
JayM37 (author)2017-02-13

Jello dare

Not to be un-nice or un-positive or un-constructive, but to try to gently correct some minor technical errors I submit for your consideration the following:

In your descriptive text you claim that your bbt is in the root, but the script clearly indicates otherwise: it's under /home/pi/ instead - which does make more sense than if you HAD put it in /

By the same token, it's redundant to talk about "navigate to home directory, then this directory..." when the script is navigating first to the root, not home, then to the afore-mentioned bbt directory. It's pointless to change to root at the top of the script and questionable to do so at the end?? It's a simple one-line command to get to bbt in the first place, regardless of where you're starting, with this:

cd /home/pi/bbt

and it might make more sense to execute this instead at the end:

cd ~

which will put you back to your default "home" directory whence you LIKELY came in the first place.

Thanks for helping so many folks with this, though!

pw

author
ReedH5 (author)2017-02-05

Script did not launch on boot up. Furthermore:

"cat: cronlog: No such file or directory."

author
lucasor (author)2016-03-05

Hello! Thanks for the tutorial. I still have a problem. How can I exit the script? There is an infinite loop and I don't know how to make the exit key. I am new on Raspberry. Can you please help? Thank you!

author
JanB143 (author)lucasor2016-09-11

sudo killall python

author
JephS (author)JanB1432016-12-01

pls where do i enter that ... to kill the script ... i have a blank screen ... but my script works

author
DanH233 (author)JephS2017-01-31

This took me a while to figure out.

Ctrl \

Will kill the script while it's running.

author
rickyb53 (author)2017-01-21

Thanks for the solution. My script is now working.

http://www.opensourcetechnologies.in/python-training-in-hyderabad.html

author
mhamza81 (author)2017-01-18

Thanks for the tutorial, It really helped a lot.

author
JeremyB86 made it! (author)2016-12-01

Hi Scott, many thanks for writing this tutorial on a foundation topic. I combined the skills learnt here with this Instructable "Build Your First IOT with a Raspberry Pi, DHT11 sensor, and Thingspeak These two instructables make a perfect pair! Shown is the image is the breadboarded project, with the thingspeak.com web page open displaying the data from the sensors on the breadboard. I used your tutorial to run at boot up the python script created in the "Build Your First IOT with a Raspberry Pi, DHT11 sensor, and Thingspeak" instructable.

Picture.jpg
author
FrédéricL17 (author)2016-11-30

Thank you so much! Looking for this for hours on internet.. A lot of solutions but no one was solving my problem.. This one works!

author
davidbachman2028 (author)2016-11-27

I just wanted to pop up and say thank you for this. Until I read this I never thought of combining cron and scripts to start code. Now I have my Rasperry Pi CPU monitor working on boot. Once again, Thanks

author
maikscho (author)2016-11-19

Hi there,

really helpful tutorial. I used your advice, to set up a video- and LED-enhanced, RPi-controlled expo booth. I have a python script, which set relais on 3 vellemann cards (vm8090) via USB, ligthing up the needed LED-Strips. Parallel, a video presentation via omxplayer is started.

I was searching for a possibility, to start this script without keyboard or mouse on start up. Eventually I found this fine tutorial. So, like above: Thank you!

author
BenHurst (author)2015-03-12

Hi

This was great, exactly what I wanted, works perfectly. One issue.

I'm running raspbian. It all starts up great, it opens a video that i've got set to run from python. I've got it so the video loops.

My problem is that I can't seem to exit or quit the video, if I want to get to the graphic interface. I've tried q, and ctrl + c and even esc. Nothing seems to be working at all.

Any way around this? I feel like i'd have to reinstall the os just to bypass this without a solution.

Thanks to all who reply

author
octopornopus (author)BenHurst2016-09-26

You might try Ctrl+Tab to try to exit, it works for me when pipresents gets stuck on fullscreen.

author
JeremyW104 (author)2016-09-25

For those of you who do not have crontab, here is the installation command: sudo apt-get install gnome-schedule

Also if you want to run a python3 script use this command in your sh script instead: sudo python3 bbt.py

author
RyanMc99 (author)2016-08-24

Thank you so much - I was struggling with this as a newbie, and your instructions were very easy to follow. My script uses bluetooth, so I needed to add a sleep 10 to the launcher.sh file before trying to execute the command. If it weren't for the log, I would have never found it.

author
JamesD308 (author)2016-07-27

I followed the steps exactly, but my script will not run when I power up. When I go to "logs" i see like 10 lines of errors. None of these seem like things I could fix as they are stuff like:

File "/usr/lib/python2.7/socket.py", line 224, in meth return getattr(self._sock,name)(*args).

The top error that I get is the only one i recognize but I am not sure this is even an error:

File garage.py, line 10, in <module> server = OSCServer ( ("192.168.1.136", 8000) )

OSC is what I am using to control my RPi with my phone.

I was wondering if anyone else had a similar problem and if you found a solution.

author
cranq (author)2016-07-20

Dude, unplugging the power to a Pi is not the same as rebooting or shutting down properly from the command line / GUI. You should never yank the power from a Pi, you run the risk of corrupting the Pi's file system. See http://raspberrypi.stackexchange.com/questions/381...

author
racurcio (author)2016-07-16

Great instructables.
I tried to implement, but I had a few problems.
So the solution for me was calling the .py directly file instead of the .sh file.
So my final crontab file was

@reboot cd home/pi; Documents/script.py

I used 2 commands (cd and script.py) because weird things were happening when I called the file directly from the root directory.

author
JayH25 (author)2016-07-14

that was one of the best tutorials I ever read! You actually wrote it like i had NO IDEA what I was doing - which means you didn't assume I had a 6-year degree in CompSci and programmed fro NASA! Thanks!

author
Prometheus3995 (author)2016-05-10

hi

i am trying to get this script to start at boot.

#!/bin/sh
#launcher.sh
#navigate to home directory then to this directory, execute python script then back home

cd /
cd /home/pi/py_scripts
sudo modprobe uinput
sudo python switch.py
cd /

as you can see it is almost identical to your script (NOOB to linux and python here)

my script is called launcher.sh and lives in 2 places

/home/pi/py_scripts & /home/pi

When i enter each command from the script into a terminal it works. If i execute it from file manager it works. It just wont work on startup.

the switch.py script works after i have manually run launcher.sh (or entered sudo modprobe uinput manually) So because of this it leads me to launcher.sh not working. but i cannot work out why. File in wrong location, crontab line is wrong (@reboot sh /home/pi/py_scripts/launcher.sh >/home/pi/logs/cronlog 2>&l)

Cronlog is nonexistent so i cant check them.

Any ideas/suggestion would be very greatly appreciated.

Thanks

author
SiddharthV7 (author)2016-04-28

Man you saved me great tutorial works magic .........Thank you

author
GuillaumeM15 (author)2016-04-27

Hi,

in my python app i use : os.system('modprobe w1-gpio')

and in the cron log file i can read : "sh: 1: modprobe: not found"

but the python script is OK and i can get the sensor data.

How should i understand the cron logs ?

Thanks

author

Oh boy, it's been awhile since I've been working with cron logs. I'll have to direct you to the Google on this one.

Sorry I can't be more help! It's not fresh in my mind.

author
DrMaker (author)2016-03-04

Thanks! It works so well!!

author
stopboris (author)2016-02-04

Fantastic, works a treat! many thanks

author
hadis16 (author)2016-02-03

thank you very much!

author
ClaudioDonate (author)2015-12-29

Very nice, worked like a charm. Thank you for the tutorial, very helpful.

author
WayneG16 (author)2015-11-21

Thanks for the info. I found it easy to follow with no issues. I do have a question.

I am using with lighshowpi and the python app runs fine from the command line but with the launcher the log tells me I need to set up some variables. Any guess as to why it would stop?

author
scottkildall (author)WayneG162015-11-22

Hi, I'm not familiar with lightshowpi, but this could be a configuration problem with that package.

If you have some specific errors from the logfile that you could post, that would be helpful.

author
CharlesR16 (author)2015-11-08

So this works perfectly, however I can't figure out how to get/find the output of any print statements I may want to use in my python script. Excuse my noobness if this is a really simple answer. Currently I'm just cancelling the boot at launch and running it manually to see the console output but I'd love to be able to output that to a .txt file or something while the program is running in the background for example. Thanks!

author
scottkildall (author)CharlesR162015-11-08

Here is some info on writing to a file in Python, which is definitely what you want to be doing.
http://www.tutorialspoint.com/python/python_files_io.htm

There's a million other tutorials out there as well, but I'd start with the basics and then build out what you specifically need just by testing and playing around.

author
CharlesR16 (author)scottkildall2015-11-08

Thanks for the quick reply, I actually know about and am using file objects like that in the program. I was thinking especially about redirecting things like error messages which are usually just output to console into a log.txt. I suppose I could use a try/except and up output to file like what you're suggesting... it seems really simple now, I guess I just needed a new pair of eyes. Thanks!

author
Django48 (author)2015-11-01

Thanks Scott,

I was pulling out my hair trying to get two scripts of directly in crontab. This method worked.

author
adanchuc (author)2015-09-21

If i dont want to do it any more, do i have to erase both the launcher.sh and the cronslog?

author
scottkildall (author)adanchuc2015-09-21

my advice would simply be to comment out the @reboot line in the crontab

put a '#' character in front of @reboot and save the crontab.

this will make it so that the launcher.sh no longer executes.

author
honeycuttj made it! (author)2015-09-19

This works great with the Christmas light project I did. Thanks.

DancingLights.mp4
author
joncschmidt (author)2015-03-13

I'm using a Raspberry Pi to build an egg incubator that self regulates. Pretty simple python script that reads a temp probe, adjusts a pwm value on the heating element accordingly, and prints a line with the temp and humidity.

I used this tutorial to start the script on boot, and everything went very well, very informative instructions. The one issue I am running into is that it loads the script in the background, so my hardware all fires up and does it's thing, and I can see the process running in the process manager, but I can't see the temp feedback from my script.

I'm sure there's a simple way to pull the python script to the front from terminal, but I can't for the life of me find it. Any ideas?

author
SqueezeHost (author)joncschmidt2015-09-14

Since you're dealing with live things I wanted to send a friendly reminder that the GPIO pins will remain in whatever state they were in last if the program crashes and/or is killed. So this could result in the heating element getting stuck in the on position. You can mitigate this by maybe having a redundant temp sensor running on a separate program that alerts you if a certain dangerous temp is ever reached. You could also use this program to reboot and hope that solves whatever problem occurred.

author
scottkildall (author)SqueezeHost2015-09-16

Thanks, this is a good point. There are a lot of ways one could solve this — for example a GPIO pin that is pulsing on/off to indicate that the RPI is on, otherwise turn the heating element off.

About This Instructable

558,138views

195favorites

License:

Bio: Scott Kildall is an new media artist and researcher. He works at Autodesk, Pier 9 and is an artist-in-residence with the SETI Institute
More by scottkildall:Pier 9 Guide: Fusion 360 to OMAX WaterjetStrewn Fields: Waterjet Etching Into StonePier 9 Resource: Setting up 2D profiles for CNC in Fusion 360
Add instructable to: