Skip to content

How to Restart Python Script after Exception and Run it Forever

Last updated on April 10, 2023

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

from subprocess import Popen
import sys

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

It uses python to open as a new subprocess. It does so in an infinite while loop, and whenever fails, the while loop restarts 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:


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

* credits

Published inPythonScript