Run a Python script at startup boot using systemd - datasith/Ai_Demos_RPi GitHub Wiki
When using a Raspberry Pi, running a script during startup is something we often want to do. The process isn't terribly difficult, but it does takes a few steps. Follow this instructions for getting it done!
- Create a file using your favorite text editor (in my case, I'll use Vim):
sudo vi /etc/systemd/user/my_script.service
- Add the following contents to it. Note to change the name/location of your script and log file. Also, if you're using Python 3 change it accordingly (i.e.,
/usr/bin/python3 ...
):
[Unit]
Description=My Python Script
After=default.target
[Service]
Type=simple
ExecStart=/usr/bin/python /home/pi/scripts/my_script.py > /home/pi/my_script.log 2>&1
[Install]
WantedBy=default.target
- Reload the daemon using
sudo
:
sudo systemctl daemon-reload
- Whereas you can enable the service for the root user, your modules and other things are likely available to the user (e.g.,
pi
) so the script might fail. Luckily, you can add the--user
option and remove thesudo
command so that the script runs as if executed by the user:
systemctl --user enable my_script.service
- Running it now to see if it works:
systemctl --user start my_script.service
- Check to see that everything looks good:
systemctl status --user my_script.service
- Troubleshoot anything that you need, and then reboot the system:
sudo reboot
You're good to go and the script will run right at startup. HTH!