Tech TLDR;

  • Archive
  • Top Posts
  • GitHub
  • LinkedIn
  • Contact

How to Restart Python Script after Exception and Run it Forever

February 23, 2018 by admin

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

Let’s say I have this simple script called test.py that I want to run forever. It will just wait 2 seconds and throw an error.

import time

time.sleep(2)
raise Exception("Oh oh, this script just died")
Code language: JavaScript (javascript)

I use the following script called forever in the same directory:

#!/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()
Code language: JavaScript (javascript)

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

./forever test.py

Which will result in the following output:

Starting test.py
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    raise Exception("Oh oh, this script just died")
Exception: Oh oh, this script just died

Starting test.py
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    raise Exception("Oh oh, this script just died")
Exception: Oh oh, this script just died

Starting test.pyCode language: JavaScript (javascript)

As you can tell, this script will run repeatedly, until it is killed with ctr+c.

Filed Under: Python

Copyright © 2025 · eleven40 Pro Theme on Genesis Framework · WordPress · Log in