Running Python Script At Boot

There are a couple of methods to run your Python script while the Raspberry Pi is booting and possible many more that I don’t know. I am going to show two of those here


(adsbygoogle = window.adsbygoogle || []).push({});

 
 

Using methode 1

The first method is probably the easiest one. It is using the cron, a job scheduler that you can find in almost all Unix systems. It allows the system to perform commands or scripts, which will repeatedly run at a set time (not always during the boot process). The cron service (a daemon in other words) runs in the background of our system.

In order to use it first you have to have your Python scrip ready and tested. Note the location of this file as it is important later. For example I have a Python script that initialises a 2×16 alphanumerical LCD and writes two lines of text. My file name is LCD_Test1.py and is stored at the location /home/pi

Now open a terminal window and type the following command to the RPi.

sudo crontab -e

and you will presented with the following:

using your cursor keys scroll to the bottom and add the following line:

@reboot python /home/pi/LCD_Test1.py &

like here:

This tells your system that every time its rebooting (start-up too no worries about that) it should run the LCD_Test1.py Python script as well. The & symbol means that the command will run in the background. If the location of your scrip is not at the /home/pi then change it respectively.

Now press Ctrl-X, then Y and Enter. You should return at the the command prompt.

It is time to test your changes. You must reboot the PRi

sudo reboot

or if for some reason you want to shutdown the Pi and then power it again then type:

sudo shutdown -h now

Whatever you choose you should see the result of your previous steps. Your system will run your Python script in the background! For me, every time I am powering my Pi I have these on my screen:

As I told before the cron is a scheduler and it is not designed only to do that. Basically it can do many more than that. The basic syntax of cron tab is:

1 2 3 4 5 /path/to/command arg1 arg2

Where:
1 = Minutes (0 – 59)
2 = Hours (0 – 23)
3 = Days (0 – 31)
4 = Month (0 – 12)
5 = Day of the week (0 – 7) (Sunday is the 0 day)

On the other hand instead of the first five fields you can use one of the seven special strings that define for you with an easiest way what you want to do. Those strings are the following:

@reboot = Run once, at startup.
@yearly = Run once a year
@monthly = Run once a month
@weekly = Run once a week
@daily = Run once a day
@midnight = Pretty much the same as @daily
@hourly = Run once an hour

For more info about cron have a look here: Cron – Wikipedia

 
 

Using methode 2

Advertisements

15 thoughts on “Running Python Script At Boot

  1. Eirinn says:

    Hey I tried your method using the pHue library for controlling phillips hue bulbs (i mention this because it must have sudo perms). However it doesn’t seem to work. The python file is called triggerHue.py and lies in /home/pi so it’s more or less the same as in your case. Here’s my command in sudo crontab -e: @reboot python /home/pi/triggerHue.py &

  2. embeddedday says:

    Hi Eirinn!

    Thanks for your message! Normally you should have no problem at all! If your python code need the internet to be active then sometimes you have to wait couple of minutes before the python code runs normally! If this is not the case then you can make the triggerHue.py an executable by typing (only once): sudo chmod +x triggerHue.py

    Hopefully this will solve the problem!

    • Eirinn says:

      Thx for the reply! As a Linux newbie these blog posts are extremely helpful. I do indeed need internet for it to run as it contacts a wired hub that controls the lights over eth0. Maybe it has something to do with the type of process I’m starting. You see, it uses the GPIO pins on the Pi and awaits a button press on GPIO 18. I don’t know if that would cause some sort of failure. Is there a way to log things so debugging is possible? :)

    • Eirinn says:

      Problem fixed. I was importing using a relative path which apparently doesn’t sit well with cronjob :)

  3. desta says:

    hi, how can i stop the program?

    • andrewshankiecom says:

      Try this @desta

      Add the following to your Python script:

      import signal

      def quit_gracefully(*args):
      exit(“Exiting Python”);

      signal.signal(signal.SIGINT, quit_gracefully)

      And then run the following command from the command line:

      kill -SIGINT $(ps aux | grep ‘[p]ython /path/to/script.py’ | awk ‘{print $2}’)

      replacing my bogus path with the path to your script.

  4. Rutger says:

    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?

  5. […] Then save it and put that python file on your Raspberry Pi or other computer and run it.  It should run and wait for requests forever.  You may want to rig up a script or other way to get it to run that python file automatically whenever the computer starts. […]

  6. Anonymous says:

    where is “Using methode 2”

  7. Anonymous says:

    how to remove python script from startup.

  8. Anonymous says:

    I spent days pulling my hair out trying this!!! It would not start. Turned out I had to add sleep 10 && in front of the program. For some reason it was failing, possibly because it required wifi and didn’t have an IP address at the time it started. Make sure to always check this though.

    • Anonymous says:

      Thanks for pulling your hair out :) that way I could save mine. Had the same problem, its too fast, too early, not all hardware is initialized fully (onewire) @reboot from cron, a little pause will do wonders. But it would be even better if the itself script waits and retries if something is not available yet.

  9. Anonymous says:

    i tried this for my project, its not at all working. but when i run the script normally,its working.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: