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 Your IP address may be different — just change the address accordingly.

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

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

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

# 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:
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
<p>I am tryin to run a camera Python program with a GUI and i get an <strong>error:</strong></p><p><strong>&quot;no display name and no $DISPLAY environment variable&quot;</strong></p><p>Can you help me?</p>
<p>Jello dare</p><p>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:</p><p>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 /</p><p>By the same token, it's redundant to talk about &quot;navigate to home directory, then this directory...&quot; 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:</p><p>cd /home/pi/bbt</p><p>and it might make more sense to execute this instead at the end:</p><p>cd ~</p><p>which will put you back to your default &quot;home&quot; directory whence you LIKELY came in the first place.</p><p>Thanks for helping so many folks with this, though!</p><p>pw</p>
<p>Script did not launch on boot up. Furthermore:</p><p>&quot;cat: cronlog: No such file or directory.&quot;</p>
<p>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!</p>
<p>sudo killall python</p>
<p>pls where do i enter that ... to kill the script ... i have a blank screen ... but my script works</p>
<p>This took me a while to figure out. </p><p>Ctrl \ </p><p>Will kill the script while it's running.</p>
<p>Thanks for the solution. My script is now working.</p><p><a href="http://www.opensourcetechnologies.in/python-training-in-hyderabad.html" rel="nofollow"><strong>http://www.opensourcetechnologies.in/python-training-in-hyderabad.html</strong></a></p>
<p>Thanks for the tutorial, It really helped a lot.</p>
<p>Hi Scott, many thanks for writing this tutorial on a foundation topic. I combined the skills learnt here with this Instructable &quot;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 &quot;Build Your First IOT with a Raspberry Pi, DHT11 sensor, and Thingspeak&quot; instructable.</p>
<p>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! </p>
<p>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</p>
<p>Hi there,</p><p>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.</p><p>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!</p>
<p>Hi</p><p>This was great, exactly what I wanted, works perfectly. One issue.</p><p>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.</p><p>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.</p><p>Any way around this? I feel like i'd have to reinstall the os just to bypass this without a solution.</p><p>Thanks to all who reply</p>
<p>You might try Ctrl+Tab to try to exit, it works for me when pipresents gets stuck on fullscreen.</p>
<p>For those of you who do not have crontab, here is the installation command: sudo apt-get install gnome-schedule</p><p>Also if you want to run a python3 script use this command in your sh script instead: sudo python3 bbt.py</p>
<p>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. </p>
<p>I followed the steps exactly, but my script will not run when I power up. When I go to &quot;logs&quot; i see like 10 lines of errors. None of these seem like things I could fix as they are stuff like:</p><p>File &quot;/usr/lib/python2.7/socket.py&quot;, line 224, in meth return getattr(self._sock,name)(*args).</p><p>The top error that I get is the only one i recognize but I am not sure this is even an error:</p><p>File garage.py, line 10, in &lt;module&gt; server = OSCServer ( (&quot;;, 8000) ) </p><p>OSC is what I am using to control my RPi with my phone.</p><p>I was wondering if anyone else had a similar problem and if you found a solution. </p>
<p>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 <a href="http://raspberrypi.stackexchange.com/questions/381/how-do-i-turn-off-my-raspberry-pi" rel="nofollow">http://raspberrypi.stackexchange.com/questions/381...</a></p>
<p>Great instructables.<br>I tried to implement, but I had a few problems.<br>So the solution for me was calling the .py directly file instead of the .sh file.<br>So my final crontab file was<br><br>@reboot cd home/pi; Documents/script.py<br><br>I used 2 commands (cd and script.py) because weird things were happening when I called the file directly from the root directory.</p>
<p>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!</p>
<p>hi</p><p>i am trying to get this script to start at boot.</p><blockquote>#!/bin/sh<br>#launcher.sh<br>#navigate to home directory then to this directory, execute python script then back home<br><br>cd /<br>cd /home/pi/py_scripts<br>sudo modprobe uinput<br>sudo python switch.py<br>cd /<br></blockquote><p>as you can see it is almost identical to your script (NOOB to linux and python here)</p><p>my script is called <strong>launcher.sh </strong>and lives in 2 places</p><p><em>/home/pi/py_scripts </em>&amp; <em>/home/pi</em></p><p>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.</p><p>the <em>switch.py</em> script works after i have manually run <em>launcher.sh</em> (or entered <em>sudo modprobe uinput</em> 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 (<strong>@reboot sh /home/pi/py_scripts/launcher.sh &gt;/home/pi/logs/cronlog 2&gt;&amp;l</strong>)</p><p>Cronlog is nonexistent so i cant check them. </p><p>Any ideas/suggestion would be very greatly appreciated.</p><p>Thanks</p>
<p>Man you saved me great tutorial works magic .........Thank you</p>
<p>Hi,</p><p>in my python app i use : os.system('modprobe w1-gpio')</p><p>and in the cron log file i can read : &quot;sh: 1: modprobe: not found&quot;</p><p>but the python script is OK and i can get the sensor data.</p><p>How should i understand the cron logs ?</p><p>Thanks</p>
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.<br /><br />Sorry I can't be more help! It's not fresh in my mind.
<p>Thanks! It works so well!! </p>
<p>Fantastic, works a treat! many thanks</p>
<p>thank you very much!</p>
<p>What does the &quot;755&quot; 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?</p>
<p>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.</p><p>One number will be the equivalent of 777 so anyone can read, write,execute. </p><p>For more info, open the terminal and enter &quot;man chmod&quot; it will show you the manual page for how to use chmod</p>
<p>Very nice, worked like a charm. Thank you for the tutorial, very helpful.</p>
<p>Thanks for the info. I found it easy to follow with no issues. I do have a question.</p><p>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?</p>
Hi, I'm not familiar with lightshowpi, but this could be a configuration problem with that package.<br><br>If you have some specific errors from the logfile that you could post, that would be helpful.
<p>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!</p>
Here is some info on writing to a file in Python, which is definitely what you want to be doing.<br>http://www.tutorialspoint.com/python/python_files_io.htm<br><br>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.
<p>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!</p>
<p>Thanks Scott,</p><p>I was pulling out my hair trying to get two scripts of directly in crontab. This method worked.</p>
<p>If i dont want to do it any more, do i have to erase both the launcher.sh and the cronslog? </p>
my advice would simply be to comment out the @reboot line in the crontab<br><br>put a '#' character in front of @reboot and save the crontab.<br><br>this will make it so that the launcher.sh no longer executes.
<p>This works great with the Christmas light project I did. Thanks.</p>
<p>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.</p><p>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. </p><p>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?</p>
<p>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. </p>
Thanks, this is a good point. There are a lot of ways one could solve this &mdash; for example a GPIO pin that is pulsing on/off to indicate that the RPI is on, otherwise turn the heating element off.
<p>I got a python script running at startup via crontab. The script periodically logs data online. This works well when I have the RasPi connected by cable, but not when I use a WIFI dongle. For the dongle to work, I need to start python in Raspbian and run the script manually. Any adice for a noob?</p>
Thank you very much! Worked for me! Since my Python script requires user input to shut down, I had to remove the &quot;cd home&quot; last line in the launcher script.
<p>Cool One ...:) Thank you </p>
<p>hello</p><p>Thanks for your tutorial I have a problem. I have written a python script with a pygame UI. I use a 7&quot; display and touch screen, I calirated it and it works in Raspbian but when I put my script in startup and reboot it, touch screen calibration doesn't work.</p><p>can you help me?</p><p>I have added 7&quot; display and touch screen with this tutorial:</p><p>https://www.instructables.com/id/The-LittleBox-Prototypes-A-Kickstarter-Project/step18/Operating-The-System/</p>
<p>Thank you so much!!! It worked like a charm!! :D</p>
<p>This seems to be a little convoluted. If you are using cron you can just call the python script from the crontab.</p><p>It is explained on Stack overflow&hellip;</p><p>http://stackoverflow.com/questions/8727935/execute-python-script-on-crontab</p><p>The launcher script is not required at all.</p><p>A more flexible way is to create an init.d script so that the service can be unloaded &amp; restarted. </p><p>http://www.stuffaboutcode.com/2012/06/raspberry-pi-run-program-at-start-up.html</p><p>Thanks for making it, but I thought readers should know that part of it is pointless and there are ways it can be done that are more flexible.</p>
<p>Please forgive the newbie question, ...</p><p>I'm receiving the following error:</p><p>var = raw_input()</p><p>EOFError: EOF when reading a line</p>

About This Instructable




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 Waterjet Strewn Fields: Waterjet Etching Into Stone Pier 9 Resource: Setting up 2D profiles for CNC in Fusion 360 
Add instructable to: