0
0
Iot-protocolsHow-ToBeginner · 4 min read

How to Run Python Script at Startup on Raspberry Pi

To run a Python script at startup on Raspberry Pi, you can add a command to crontab with the @reboot keyword or create a systemd service that runs your script automatically. Both methods ensure your script starts every time the Raspberry Pi boots.
📐

Syntax

There are two common ways to run a Python script at startup on Raspberry Pi:

  • Using crontab: Add a line with @reboot python3 /path/to/script.py to the crontab file.
  • Using systemd service: Create a service file that specifies the script to run and enable it to start at boot.

Each method runs your Python script automatically when the Raspberry Pi powers on.

bash
# Using crontab syntax
@reboot python3 /home/pi/myscript.py

# Basic systemd service file example
[Unit]
Description=My Python Script

[Service]
ExecStart=/usr/bin/python3 /home/pi/myscript.py
Restart=always

[Install]
WantedBy=multi-user.target
💻

Example

This example shows how to use crontab to run a Python script named hello.py at startup. The script prints a message to a log file.

python
# hello.py
with open('/home/pi/startup_log.txt', 'a') as f:
    f.write('Raspberry Pi started running hello.py\n')

# To add to crontab, run:
# crontab -e
# Then add the line:
@reboot python3 /home/pi/hello.py
⚠️

Common Pitfalls

Common mistakes when running Python scripts at startup include:

  • Using relative paths instead of full paths, causing the script not to find files.
  • Not specifying the full path to the Python interpreter.
  • Forgetting to make the script executable or missing permissions.
  • Running scripts that require a graphical environment in a non-GUI startup.

Always use absolute paths and test your script manually before adding it to startup.

bash
# Wrong crontab entry (missing full path):
@reboot python3 myscript.py

# Correct crontab entry:
@reboot /usr/bin/python3 /home/pi/myscript.py
📊

Quick Reference

Summary tips to run Python scripts at startup on Raspberry Pi:

  • Use crontab -e and add @reboot python3 /full/path/to/script.py.
  • Or create a .service file in /etc/systemd/system/ and enable it with sudo systemctl enable yourservice.
  • Always use full paths for scripts and Python interpreter.
  • Test scripts manually before automating startup.

Key Takeaways

Use crontab with @reboot or systemd service to run Python scripts at Raspberry Pi startup.
Always specify full paths for your script and Python interpreter to avoid errors.
Test your script manually before setting it to run automatically.
Avoid running GUI-dependent scripts at boot unless the graphical environment is ready.
Ensure your script has the right permissions to execute.