Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically restart program when error occur

Tags:

python

restart

The program is like this:

HEADER CODE
urllib2.initialization()
try:
    while True:
        urllib2.read(somebytes)
        urllib2.read(somebytes)
        urllib2.read(somebytes)
        ...
except Exception, e:
    print e
FOOTER CODE

My question is when error occurs (timeout, connection reset by peer, etc), how to restart from urllib2.initialization() instead of existing main program and restarting from HEADER CODE again?

like image 395
jack Avatar asked Jan 01 '26 18:01

jack


2 Answers

You could wrap your code in a "while not done" loop:

#!/usr/bin/env python

HEADER CODE
done=False
while not done:
    try:
        urllib2.initialization()
        while True:
            # I assume you have code to break out of this loop
            urllib2.read(somebytes)
            urllib2.read(somebytes)
            urllib2.read(somebytes)
            ...
    except Exception, e:    # Try to be more specific about the execeptions 
                            # you wish to catch here
        print e
    else:
    # This block is only executed if the try-block executes without
    # raising an exception
        done=True
FOOTER CODE
like image 131
unutbu Avatar answered Jan 03 '26 06:01

unutbu


How about just wrap it in another loop?

HEADER CODE
restart = True
while restart == True:
   urllib2.initialization()
   try:
       while True:
           restart = False
           urllib2.read(somebytes)
           urllib2.read(somebytes)
           urllib2.read(somebytes)
           ...
   except Exception, e:
       restart = True
       print e
FOOTER CODE
like image 34
Charles Ma Avatar answered Jan 03 '26 07:01

Charles Ma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!