How to run the program after an unexpected exit in Python?

advertisements

I'm writing an IRC bot in Python, due to the alpha nature of it, it will likely get unexpected errors and exit.

What's the techniques that I can use to make the program run again?


You can use sys.exit() to tell that the program exited abnormally (generally, 1 is returned in case of error).

Your Python script could look something like this:

import sys

def main():
    # ...

if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        print >> sys.stderr,  e
        sys.exit(1)
    else:
        sys.exit()

You could call again main() in case of error, but the program might not be in a state where it can work correctly again. It may be safer to launch the program in a new process instead.

So you could write a script which invokes the Python script, gets its return value when it finishes, and relaunches it if the return value is different from 0 (which is what sys.exit() uses as return value by default). This may look something like this:

import subprocess

command = 'thescript'
args = ['arg1', 'arg2']

while True:
    ret_code = subprocess.call([command] + args)

    if ret_code == 0:
        break