I'm making a robot using a Raspberry Pi.

I have written code for it in Python and I would like the Python script to run as soon as the Pi is powered.

I only want the whole script to repeat the whole time.


First in raspi-config select Boot Options then Desktop/CLI then Console Autologin.

Then in a Terminal window run:

sudo nano /etc/profile

At the bottom add:

sudo python /home/pi/yourscript.py

Press ctrl+X and then press Y followed by ENTER twice.

/home/pi/ is the directory of your python file and yourscript.py is the name of your python code.

To check this works reboot the Pi. If you want the Python code to repeat, in your Python code set up some kind of While loop and that would work. Alternatively you could look into using Cron. However, depending on how you coded you program it might run indefinitely anyway.

  • What's the point in the console autologin? – user67191 Jun 15 '17 at 18:27
  • The auto-login is optional. It essentially means the Pi is able to start the Python script running without a user having to log in. This might be useful if you can't SSH into the Pi or connect a monitor to the Pi, the Pi can just be switched on and the script runs. – Darth Vader Jun 15 '17 at 18:32

I would use a Cron Job:

( sudo crontab -l; echo "@reboot" $(which python) /home/pi/foo ) | sudo crontab -

If your sketch doesn't need to be run as root, you can omit both sudo parts and run it as your current user, at boot.

Just replace /home/pi/foo with the full path to your python sketch. The @reboot will run the path to your sketch in your current version of Python, upon a complete reboot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.