Raspberry Pi startup script

Last updated 6 months ago

There are different ways to automatically execute a script after booting.

Quick and Dirty (rc.local)

Edit the file /etc/rc.local with your favorite editor. In this case we want to execute the python script myscript.py. You must be root to do this. Add the line /usr/bin/python /home/pi/myscript.py& before the exit 0 line in the file. Make sure to use absolute paths

sudo nano /etc/rc.local
/etc/rc.local
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
printf "My IP address is %s\n" "$_IP"
fi
#Add your command here
/usr/bin/python /home/pi/myscript.py &
exit 0

Better (Systemd)

First we need to create a unit file in the folder /etc/systemd/system/ we name it myscript.service. In this case we want to execute the python script myscript.py. You have to be root to create this file.

sudo nano /etc/systemd/system/myscript.service
/etc/systemd/system/myscript.service
[Unit]
Description=Print shipping labels from barcode ids
After=network.target
[Service]
ExecStart=/usr/bin/python /home/pi/myscript.py
Restart=always
User=pi
[Install]
WantedBy=multi-user.target

To enable and start the service:

sudo systemctl enable myscript.service
sudo systemctl start myscript.service