How To Autorun A Python Script On Raspberry Pi Boot

22

There are lots of techniques for running a script when the Pi boots and which one you choose will depend on exactly what the script does and what you expect. In this post I’ll explain a technique where the Pi automatically logins as the Pi user and immediately executes a Python script.

This has one major advantage over another popular method (see Running A Python Script At Boot Using Cron) in that because the terminal is up and running text output from the script is visible before you are returned to a usable command line prompt.

Auto Login Setup (optional)

The first step is to enable the Pi to login automatically without requiring any user intervention. This step is optional.

At the command prompt or in a terminal window type :

sudo raspi-config

followed by Enter.

Select “Boot Options” then “Desktop/CLI” then “Console Autologin”

Prepare Script

My test script is called “myscript.py” and is located in /home/pi/. This is what it contains :

#!/usr/bin/python
print("******************************************************")
print("* This is a test script. There are many like it,     *")
print("* but this one is mine. My script is my best friend. *")
print("* It is my life. I must master it as I must master   *")
print("* my life.                                           *")
print("******************************************************")

You can download this directly to your Pi by using the following command :

wget https://bitbucket.org/MattHawkinsUK/rpispy-misc/raw/master/python/myscript.py

I strongly suggest getting this working before trying any other scripts!

Auto-run Script Setup

Now we need to tell the operating system to run the script for the Pi user. In the command prompt or in a terminal window type :

sudo nano /etc/profile

Scroll to the bottom and add the following line :

sudo python /home/pi/myscript.py

where “/home/pi/myscript.py” is the path to your script.

Type “Ctrl+X” to exit, then “Y” to save followed by “Enter” twice.

A Script Without End

You will only be returned to the command line when your script is complete. If your script contains an endless loop then you may want to use this line in the profile file instead :

sudo python /home/pi/myscript.py &

This will allow the script to run in the background but you will not see any text output from it.

Reboot and Test

To test if this has worked reboot your Pi using :

sudo reboot

When it starts up your script will run and you will see something like this :

Autorun script result

Due to the technique we’ve used the script is run whenever the Pi user logs in. This means if you create other terminal sessions (via SSH for example) the script will run each time.

Troubleshooting

If it doesn’t work here are some things to try :

  • Run your script manually and check it works correctly
  • Use my example script and check that works
  • Double check the initial steps
Share.

22 Comments

    • Hi, I tried the method you’ve described above, however I use a “while True:” loop in my program. My Pi is stuck a black screen during the boot, Is this because the script never completes? Please help resurrect my pi

  1. Thanks Matt great tutorial.

    To the others that get stuck with the black screen this is how I reverted back to how it was.

    When the pi boots up and the script starts running just Ctrl+c which takes you back to the command line, you can # out the added lines in the nano files and delete the # so the file reverts back to how it was.

  2. Thank you so much for this solution. We were trying for 3-4 days to run Python script at boot time but that all went into vain. This solution worked out. many thanx.

  3. Thanks for the guide, my script ran perfectly at startup!

    I am having the same problem of the black screen at boot (probably due to my while true loop). I keep trying to control-C on my keyboard but that doesn’t work. My Mac also refuses to connect to the pi via SSH. Anything else I can try? Otherwise I will just reinstall the os, no big deal.

    • This technique is only suitable for scripts that perform a task and then exit. If they get stuck in a loop they may stop the boot sequence completing.

  4. For those who are facing black screen problem
    Just boot up the pie
    Allow your script to run at same time press ctrl+alt+f1 and then ctrl+c
    You will be prompted with command prompt where you can make changes

  5. Hello,

    I am using Raspberry Pi 3 Model B and today i wanted to autorun a Python script once the Pi is booted up, but suddenly, it says:

    ” -bash: PKG_CONFIG: command not found ”

    And it cannot continue.

    Looking forward to getting your help as soon as possible.

    Thank you,

    • I’ve not seen that error before. Does your Python script run without error when you run it on its own?

  6. I’ve ruined my Pi 🙁

    Ctrl+C doesn’t work.
    ctrl+alt+f1 doens’t work.
    SSH doesn’t work as I don’t have the IP.

    I will need to format my Pi. Proceed with caution!

  7. Do this also work on a .js file? I’m using a raspberry PI 2 and seems like after following all of the steps. I end up running nothing after the boot of RPI. Can you help me to work on these. thanks! my file for example is on test1.js and is located at /home/pi

    • If it is a Javascript file that would have to run in a browser. So this method isn’t suitable. You would need to launch into the GUI, run a browser and get it to auto load an HMTL file with the JS file included within that.

  8. This method has one major flaw. It could potentially run multiple instances of the script. Which could lead to weird problems (such as multiple writes to a file if using such per script). I got bitten by this and couldn’t figure out the root cause until I issued sudo ps aux | grep -i myscript.py.

    I’m still looking for a solution that doesn’t run multiple instances of the python script.

  9. Please state in the article that you CANNOT use loops with this function. You have already ruined several people’s pi’s and now, not mine. It’s not even for personal use but for a company. I’ve spent weeks programming and now I’m locked out. Thanks a lot. Why haven’t you, after so many people said it, noted that this will happen if you use loops?

    • I’ve updated the article to mention scripts that don’t exit. Re-creating an SD card is all part of experimenting with the Pi. Your own programming or any number of other factors could result in data loss at any time. When developing you really need to backup any work at regular intervals.

Leave A Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.