tags:

views:

253

answers:

3

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?

A: 

The easiest way is to catch errors, and close the old and open a new instance of the program when you do catch em.

Note that it will not always work (in cases it stops working without throwing an error).

kkaploon
+1  A: 

You can create wrapper using subprocess(http://docs.python.org/library/subprocess.html) which will spawn your application as a child process and track it's execution.

Mihail
+5  A: 

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
Bastien Léonard
Very Pythonic :-)
e-satis