Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - how do I make a program run forever, no matter what exceptions occur?

So I've got something of the form:

def func():
  while True:
    do_stuff()

try:
  func()
except:
  func()

I had expected that if anything happened to my func loop, it would start again, however in actual fact errors cause it to crash. How can I make it just restart if anything goes wrong?

like image 474
cjm2671 Avatar asked Mar 25 '26 15:03

cjm2671


2 Answers

You can try placing the try-except inside a while loop and use pass in the except block.

Ex:

def func():
  while True:
    do_stuff()

while True:
    try:
        func()
    except:
        pass
like image 137
Rakesh Avatar answered Mar 27 '26 03:03

Rakesh


What are you trying to achieve? Keeping a program run is generally not the responsibility of the program itself. If you are on a UNIX-like operating system, you can use Supervisord to automatically run processes and let them restart if they fail. If you are on Windows, this answer may help you out!

like image 34
Wouter Van der Schraelen Avatar answered Mar 27 '26 03:03

Wouter Van der Schraelen