How to Run Python Script on Startup Raspberry Pi
To run a Python script on Raspberry Pi startup, add the script command to
/etc/rc.local, create a systemd service, or use crontab with the @reboot option. These methods ensure your script runs automatically when the Pi boots.Syntax
Here are three common ways to run a Python script on startup:
- rc.local: Add
python3 /path/to/script.py &beforeexit 0in/etc/rc.local. - systemd service: Create a service file with
ExecStart=/usr/bin/python3 /path/to/script.pyand enable it. - crontab: Use
@reboot python3 /path/to/script.py &in the crontab file.
bash
# rc.local example snippet
sudo nano /etc/rc.local
# Add before exit 0
python3 /home/pi/myscript.py &
# systemd service example
sudo nano /etc/systemd/system/myscript.service
[Unit]
Description=My Python Script
[Service]
ExecStart=/usr/bin/python3 /home/pi/myscript.py
Restart=always
[Install]
WantedBy=multi-user.target
# crontab example
crontab -e
# Add line
@reboot python3 /home/pi/myscript.py &Example
This example shows how to create a simple Python script that prints a message to a file on startup using crontab.
bash
# Create a Python script cat << EOF > /home/pi/startup_test.py import time with open('/home/pi/startup_log.txt', 'a') as f: f.write(f'Script ran at {time.ctime()}\n') EOF # Make sure script is executable chmod +x /home/pi/startup_test.py # Add to crontab (crontab -l 2>/dev/null; echo '@reboot python3 /home/pi/startup_test.py &') | crontab - # Reboot the Pi to test sudo reboot
Common Pitfalls
Common mistakes when running Python scripts on startup include:
- Not using the full path to the Python interpreter or script.
- Forgetting to add
&to run the script in the background. - Permissions issues: the script or files it accesses may not have the right permissions.
- Environment differences: startup scripts run with limited environment variables, so absolute paths are important.
bash
# Wrong way (rc.local without &): python3 /home/pi/myscript.py # Right way: python3 /home/pi/myscript.py &
Quick Reference
| Method | File/Command | Key Notes |
|---|---|---|
| rc.local | /etc/rc.local | Add script before exit 0, use & to background |
| systemd service | /etc/systemd/system/*.service | Create service file, enable with systemctl |
| crontab | crontab -e | Use @reboot, full paths, & to background |
Key Takeaways
Use full paths for Python and scripts to avoid environment issues.
Add & at the end of commands to run scripts in the background on startup.
Choose systemd for robust service management, rc.local for quick setup, or crontab for simple reboot tasks.
Check script permissions and test manually before adding to startup.
Reboot the Raspberry Pi to verify your script runs automatically.