Skip to content

How to Restart Python Script after Exception and Run it Forever

Last updated on March 13, 2019

Here is a simple trick that I used to restart my python script after unhandled exception.

#!/usr/bin/python
from subprocess import Popen
import sys

filename = sys.argv[1]
while True:
    print("\nStarting " + filename)
    p = Popen("python " + filename, shell=True)
    p.wait()

It uses python to open script.py as a new subprocess. It does so in an infinite while loop, and whenever script.py fails, the while loop restarts script.py as a new subprocess.

I’ll have to make the forever script executable by running chmod +x forever. Optionally forever script can be moved to some location in the PATH variable, to make it available from anywhere.

Next, you can start program with:

./forever script.py

This script will run repeatedly, until it is killed with ctr+c.

Published inPythonScript

Be First to Comment

Leave a Reply