Domanda

Il programma è così :

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

La mia domanda è quando si verifica un errore (timeout, connessione ripristinata dal peer, ecc.), come riavviare da urllib2.initialization () invece del programma principale esistente e riavviare nuovamente da HEADER CODE?

È stato utile?

Soluzione

Modo semplice con restrizioni ai tentativi

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

Altri suggerimenti

Puoi racchiudere il tuo codice in un " mentre non hai finito " ciclo:

#!/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

Che ne dici di avvolgerlo in un altro 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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top