Raspberry Pi‎ > ‎

Run a script every time your Raspberry Pi starts

posted Oct 25, 2015, 5:12 AM by Chris G   [ updated Aug 12, 2016, 5:33 PM ]

The "easy" option...type the following in a command prompt:


crontab -e

Add the following entry to the crontab file:









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



If you want to create a service, do the following:




Create a new file by running:


sudo nano /etc/init.d/launch
Paste the following as the content of the file:

### BEGIN INIT INFO
# Provides: Launch - date / time / ip address
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Launch Python Script
# Description: date / time / ip address
### END INIT INFO
 

#! /bin/sh
# /etc/init.d/launch
 
 
export HOME
case "$1" in
    start)
        echo "Starting Launch"
cd /home/pi/
        /home/pi/launch.py  2>&1 &
    ;;
    stop)
        echo "Stopping Launch"
	MY_PID=`ps auxwww | grep launch.py | head -1 | awk '{print $2}'`
	kill -9 $MY_PID
    ;;
    *)
        echo "Usage: /etc/init.d/launch {start|stop}"
        exit 1
    ;;
esac
exit 0
then run

sudo chmod +x /etc/init.d/launch
sudo update-rc.d lcd defaults

make sure your script is also executable

sudo chmod +x /home/pi/launch.py

sample script as launch.py

#!/usr/bin/python


import subprocess

try:
  subprocess.call(['/home/pi/scripts/webserver.py &'], shell=True)
except SystemExit, e:
  print "sys.exit %s" % e
exit()