Introduction: Raspberry Pi: Launch Python Script on Startup

Picture of 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

Picture of Make a Launcher Sript
I'm building out a new project called Black Box Timelapse (Instructable coming soon...).

My python script is called : 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 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
Will launch your editor, type in this script

# navigate to home directory, then to this directory, then execute python script, then back home

cd /
cd home/pi/bbt
sudo python
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

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

Step 3: Add Logs Directory

Picture of 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

Picture of 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/ >/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 code:

# every 2 minutes
*/2 * * * * /home/pi/justdiedbot/ >/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/ >/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


MatiasG42 (author)2017-12-15


First of all, great tutorial. Very clear.

However I am having an error in my MySQL connection.

_mysql_exceptions.OperationalError: (2002, 'Can\'t connect to local MySQL server through socket \'/var/run/mysqld/mysqld.sock\' (2 "No such file or directory")')

I think that maybe have to be the user who run the script but I to noob in linux to know.

Thanks in advance.

GioloP (author)2017-12-13

I am having an error running my script on boot.

ImportError: no module named imutils

I have tested my script an it runs without errors, I also checked that it imports everything that is needed. But when I run it on boot (following the steps above) it seems it can't import modules. Is there anything else that I needed to do?

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.

pash0107 (author)GabrielB1642017-11-26

Hi Sir Gabriel. Can you please help me with this? I also have a python script that requires wireless connection (paho.mqtt). Can you please guide me with some stuff? . Thanks a lot.:)

BryceJ6 made it! (author)2017-11-14

Since it required an image, I took a simple screenshot.

I just wanted to say thank you for this, as other methods I found weren't working for me. Thanks to you I will now be able to easily monitor the temperature in my new hedgehogs cage and can expand the system for other automation and monitoring scripts.

The Jack (author)2017-09-27

Hi, total noob here !
Before getting to this tutorial, i ran the .py manually in the terminal.

I managed to get to launch my python script, but when my raspy reboots nothing happens( i dont see a terminal where i can read my data inputs like my working .py would). Also, when i try to reach the logs , an error says they dont exist, eventhough the log directory already exists.

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.

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?

ParkerR11 (author)2017-08-09

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

LeonardoA114 (author)2017-06-22

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

Traceback (most recent call last):
File "", 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 to recognize pygame?

YashS121 (author)LeonardoA1142017-07-01


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

Try it first "sudo python "

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 script.

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


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?

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:




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


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

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?

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!


ReedH5 (author)2017-02-05

Script did not launch on boot up. Furthermore:

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

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!

JanB143 (author)lucasor2016-09-11

sudo killall python

JephS (author)JanB1432016-12-01

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

DanH233 (author)JephS2017-01-31

This took me a while to figure out.

Ctrl \

Will kill the script while it's running.

rickyb53 (author)2017-01-21

Thanks for the solution. My script is now working.

mhamza81 (author)2017-01-18

Thanks for the tutorial, It really helped a lot.

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 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.

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!

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

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!

BenHurst (author)2015-03-12


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

octopornopus (author)BenHurst2016-09-26

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

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

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 file before trying to execute the command. If it weren't for the log, I would have never found it.

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/", 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, line 10, in <module> server = OSCServer ( ("", 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.

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

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/

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

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!

Prometheus3995 (author)2016-05-10


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

#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
cd /

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

my script is called 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 script works after i have manually run (or entered sudo modprobe uinput manually) So because of this it leads me to not working. but i cannot work out why. File in wrong location, crontab line is wrong (@reboot sh /home/pi/py_scripts/ >/home/pi/logs/cronlog 2>&l)

Cronlog is nonexistent so i cant check them.

Any ideas/suggestion would be very greatly appreciated.


SiddharthV7 (author)2016-04-28

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

GuillaumeM15 (author)2016-04-27


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 ?


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.

DrMaker (author)2016-03-04

Thanks! It works so well!!

stopboris (author)2016-02-04

Fantastic, works a treat! many thanks

hadis16 (author)2016-02-03

thank you very much!

ClaudioDonate (author)2015-12-29

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

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?

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.

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!

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.

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.

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!

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.

adanchuc (author)2015-09-21

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

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