Running a Python Script on Startup for Raspberry Pi - hexs/Raspberry-Pi GitHub Wiki
To run a Python script automatically on startup for a Raspberry Pi, you can use several methods. Here are three common approaches:
crontab
is a time-based job scheduler in Unix-like operating systems. You can use it to schedule scripts to run at
startup.
-
Open the terminal on your Raspberry Pi.
-
Edit the
crontab
file with the command:crontab -e
-
If prompted, choose an editor (nano is a simple choice).
-
Add the following line to the file to run your script at boot:
@reboot python3 /path/to/your/script.py
Replace /path/to/your/script.py with the full path to your Python script.
-
Save and exit the editor. The script will now run at every reboot.
systemd
is a system and service manager for Linux operating systems. It can be used to create a service that runs your
script at startup.
- Create a new service file:
sudo nano /etc/systemd/system/myscript.service
- Add the following content to the file:
Ensure the ExecStart path points to your Python script.
[Unit] Description=My Python Script After=network.target [Service] ExecStart=/usr/bin/python3 /path/to/your/script.py Restart=always User=pi [Install] WantedBy=multi-user.target
- Save and close the file.
- Enable the service to run at startup:
sudo systemctl daemon-reload sudo systemctl enable myscript.service
- Start the service immediately if desired:
sudo systemctl start myscript.service
- Check the status of the service to ensure it is running:
The script will now run at every boot.
sudo systemctl status myscript.service
The rc.local
file can be used to execute scripts at the end of the multi-user runlevel.
- Open the rc.local file for editing:
sudo nano /etc/rc.local
- Add your command above the
exit 0
line:The ampersand (&) allows the script to run in the background.python3 /path/to/your/script.py &
- Ensure the rc.local file is executable:
sudo chmod +x /etc/rc.local
- Reboot the Raspberry Pi to test:
The script should now run at startup.
sudo reboot
- Create your Python script and test it to ensure it works correctly.
- Create a .desktop file in the autostart directory:
mkdir -p /home/pi/.config/autostart
nano /home/pi/.config/autostart/script1.desktop
- Add the following content to the .desktop file:
Replace "script1" with a descriptive name and adjust the path to your script accordingly
[Desktop Entry] Type=Application Name=script1 Exec=lxterminal -e 'bash -c "cd /home/pi/<project> && /home/pi/<project>/.venv/bin/python main.py"'
- Save
ctrl + s
and exitctrl + x
the text editor. - Make the .desktop file executable:
chmod +x /home/pi/.config/autostart/script1.desktop
Each method has its own advantages. crontab is simple and effective for most use cases, systemd offers more control and logging, and rc.local is straightforward for quick setups. Choose the method that best suits your needs.