Python:异常后继续循环

时间:2012-07-03 08:12:59

标签: python exception loops

我有以下脚本(如下)。这将返回URL的状态代码。它遍历文件并尝试连接到每个主机。唯一的问题是它在到达异常时显然会停止循环。

我已经尝试了很多东西来把它如何循环,但无济于事。有什么想法吗?

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()

编辑:

我在平均时间提出这个问题,有什么问题吗? (我还在学习: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"

谢谢,

MHibbin

3 个答案:

答案 0 :(得分:11)

您可以处理引发它的异常。此外,在打开文件时使用上下文管理器,它可以实现更简单的代码。

with open(hostsFile, 'r') as f:
    for line in f:
        line = line.strip()
        if not line:
            continue

        epoch = str(time.time())

        try:
            conn = urllib.urlopen(line)
            print epoch + ": Connection successful, status code for " + line + " is " + str(conn.code) + "\n"
        except IOError:
            print epoch + ": Connection unsuccessful, unable to connect to server, potential routing issues\n"

答案 1 :(得分:4)

您需要处理urllib.urlopen(line)引发的异常,类似这样的事情。

try:
    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)
        except IOError:
           print "Exception occured"
           pass
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()

答案 2 :(得分:1)

您可以尝试在while循环中捕获异常,就像这样。

try:
    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:
            epoch = time.time()
            epoch = str(epoch)
            print epoch + ": Connection unsuccessful, unable to connect to server, potential routing issues\n"
except IOError:
    pass
else:
    f.close()