开发者

Automatically restart program when error occur

开发者 https://www.devze.com 2022-12-09 19:17 出处:网络
The program is like this: HEADER CODE urllib2.initialization() try: while True: urllib2.read(somebytes) urllib2.read(somebytes)

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

精彩评论

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

关注公众号