Skip to content

Instantly share code, notes, and snippets.

@amrakm
Last active June 20, 2022 13:58
Show Gist options
  • Save amrakm/5fd9a901be9315149ec99b36a81d3a80 to your computer and use it in GitHub Desktop.
Save amrakm/5fd9a901be9315149ec99b36a81d3a80 to your computer and use it in GitHub Desktop.
restart python script if it crashes
# https://stackoverflow.com/a/63021289/5554394
from subprocess import run
from time import sleep
# Path and name to the script you are trying to start
file_path = "test.py"
restart_timer = 2
def start_script():
try:
# Make sure 'python' command is available
run("python "+file_path, check=True)
except:
# Script crashed, lets restart it!
handle_crash()
def handle_crash():
sleep(restart_timer) # Restarts the script after 2 seconds
start_script()
start_script()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment