You can run the script as service using systemd. Just create a Unit file with:
rpi ~$ sudo systemctl --force --full edit myscript.service
In the empty editor insert these statements, save them and quit the editor:
[Unit]
Description=My Python Script
After=multi-user.target
[Service]
RestartSec=10
Restart=always
ExecStart=python3 /full/path/to/myscript.py
[Install]
WantedBy=multi-user.target
This will always restart your script after 10 seconds. Always restarting a script may not be the best option if it should terminate regular. You can use the settings no, on-success, on-failure, on-abnormal, on-watchdog, on-abort or always. There are many other options to restart the script as you can find in man systemd.service
.
Enable and run the service with
rpi ~$ sudo systemctl enable --now myscript.service
Check it with
rpi ~$ systemctl status myscript.service
while True:
, and use exception KeyboardInterrupt for exiting while loop when you press [CTRL+C]. You can also use a system unit file for starting your python script, the file can contain : Restart, Timeout etc ... (I think it's the best method). You can see the options here – Ephemeral Oct 26 '19 at 12:06try: Except
for getting your error description ? – Ephemeral Oct 26 '19 at 12:28(I think it's the best method)
... no the best method is to check the errors correctly first and then maybe use a system unit file. – Ephemeral Oct 26 '19 at 12:30python /home/pi/yourfile.py
inExecStart
– Ephemeral Oct 26 '19 at 12:42