开发者

Automatically restart program when error occur

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 re开发者_如何学运维start from urllib2.initialization() instead of existing main program and restarting from HEADER CODE again?


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


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


Simple way with attempts restrictions

HEADER CODE
attempts = 5
for attempt in xrange(attempts):
    urllib2.initialization()
    try:
        while True:
            urllib2.read(somebytes)
            urllib2.read(somebytes)
            urllib2.read(somebytes)
            ...
    except Exception, e:
        print e
    else:
        break
FOOTER CODE
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜