Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top