Running Python script on Raspberry Pi5 bootup
Prepare the Python Script
Let’s create a python file which we need to execute continuously after pi boot up automatically.
sudo nano /home/pi5/python/main.py
As an example, I’m adding following code block. This will print Script is running every 10sec...and it logs to the log file in the same directory.
#!/usr/bin/env python3
import time
import logging
# Set up logging
logging.basicConfig(
filename='/home/pi5/python/log',
level=logging.INFO,
format='%(asctime)s - %(message)s'
)
while True:
# Your code here
message = "Script is running every 10sec..."
print(message) # This will go to systemd journal
logging.info(message) # This will go to the log file
time.sleep(10)Now make the script executable
sudo chmod +x main.py
Create a Systemd service file
Create a new service file in the systemd directory
Get We develop’s stories in your inbox
Join Medium for free to get updates from this writer.
sudo nano /etc/systemd/system/py_bootup.service
Then add the following content
[Unit]
Description=Python Script Service
After=network.target
[Service]
ExecStart=/usr/bin/python3 /home/pi5/python/main.py
WorkingDirectory=/home/pi5/python
StandardOutput=inherit
StandardError=inherit
Restart=always
User=pi5
[Install]
WantedBy=multi-user.targetNow enable and start the service we createdsudo systemctl daemon-reload
sudo systemctl enable py_bootup.service
sudo systemctl start py_bootup.service
Now check status of the service
sudo systemctl status py_bootup.service
Let’s verify the log if our script is really getting executed. As you see below, the print statement is appeared every 10 sec of executing the command ( cat log )
Now, restart the pi, and again verify the log. You should be able to see the file is appended with new print statements every 10sec.









