Python: Wiederholen Sie die Schleife nach einer Ausnahme

Ich habe das folgende Skript (unten). Der Statuscode von URLs wird zurückgegeben. Es durchläuft eine Datei und versucht, eine Verbindung zu jedem Host herzustellen. Das einzige Problem ist, dass es offensichtlich die Schleife stoppt, wenn es eine Ausnahme erreicht.

Ich habe zahlreiche Dinge versucht, um das Wie in eine Schleife zu bringen, aber ohne Erfolg. Irgendwelche Gedanken?

import urllib
import sys
import time

hostsFile = "webHosts.txt"


try:
    f = file(hostsFile)
    while True:
        line = f.readline().strip()
        epoch = time.time()
        epoch = str(epoch)
        if len(line) == 0:
            break
        conn = urllib.urlopen(line)
        print epoch + ": Connection successful, status code for " + line + " is " + str(conn.code) + "\n"
except IOError:
    epoch = time.time()
    epoch = str(epoch)
    print epoch + ": Connection unsuccessful, unable to connect to server, potential routing issues\n"
    sys.exit()
else:
    f.close()

BEARBEITEN:

Ich habe mir das inzwischen ausgedacht, irgendwelche Probleme damit? (Ich lerne noch: p) ...

f = file(hostsFile)
while True:
    line = f.readline().strip()
    epoch = time.time()
    epoch = str(epoch)
    if len(line) == 0:
        break
    try:
        conn = urllib.urlopen(line)
        print epoch + ": Connection successful, status code for " + line + " is " + str(conn.code) + "\n"
    except IOError:
        print epoch + "connection unsuccessful"

Vielen Dank,

MHibbin

Antworten auf die Frage(3)

Ihre Antwort auf die Frage