Python is an easy-to-use language. Developers can build up an automation tool quickly using libraries provided by others. However, if it is crashed during execution and there is no exception handling script, it will not restart automatically. This article will introduce a way to handle exceptions and restart your Python script once it is terminated. The script has been tested on Raspbian Buster/Bullseye and Ubuntu Desktop 22.04.
Prerequisite: You have to install Spyder on your system. You may encounter some issues during the installation of Spyder on Ubuntu 22.04. Check out my article to fix it. You may also look at my other article about how to set up an auto-start Python script on Spyder.
Step 1: Create a bash script on your Desktop folder
cd /home/pi/Desktop nano restartOnCrash.sh
#!/bin/bash while true; do ps --no-headers -C spyder3 || spyder3 sleep 1m done
It will check whether the Spyder IDE is live every minute.
Step 2: Make it executable by
chmod +x restartOnCrash.sh
Step 3: Add an XDG autostart application to your system
sudo nano /etc/xdg/autostart/restartOnCrash.desktop
[Desktop Entry] Type=Application Name=RestartOnCrash Comment=Restart spyder on crash Exec=lxterminal --working-directory=/home/pi/Desktop/ -e ./restartOnCrash.sh Terminal=true
Step 4: Restart your device. Spyder will be executed automatically on start. You may add
os.system('pkill -f "spyder3"')
to your exception handling (remember to import os). Spyder will restart automatically.