简体   繁体   中英

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?

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

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!

Try to put loop contents inside try except statements

def func():
    while True:
        try:
            do_stuff()
        except:
            continue
func()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM