Running a Python script at startup on a Raspberry Pi

Setting Up using SYSTEMD

  1. Create a Service File: Open a new file in /etc/systemd/system/, for example myscript.service, using nano:
sudo nano /etc/systemd/system/myscript.service

2. Add the Following to the Service File:

Adding a 20 seconds delay using “ExecStartPre”

[Unit]
Description=My Python Script Service
After=multi-user.target

[Service]
Type=simple
ExecStartPre=/bin/sleep 20
ExecStart=/usr/bin/python3 /path/to/your/script.py
StandardOutput=append:/path/to/your/logfile.log
StandardError=inherit

[Install]
WantedBy=multi-user.target

Replace /path/to/your/script.py with your script’s path and adjust paths as necessary.

3. Reload Systemd to read the new service file:

sudo systemctl daemon-reload

4. Enable and Start Your Service:

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

Monitoring and Troubleshooting

Check if your script is running properly and debug as needed:

systemctl status myscript.service

Reading Output of the Python Script

Since the output of the script (both print statements and errors) is redirected to a log file (/path/to/your/logfile.log in the example), you can check this file to read the output. To view or monitor this log file, you can use:

  • cat to display the log:
cat /path/to/your/logfile.log
  • less to view the log in a scrollable manner:
less /path/to/your/logfile.log
  • tail to follow the log:
tail -f /path/to/your/logfile.log

This command is particularly useful to see new outputs added to the log in real-time.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *