Python:出现异常后继续循环

问题描述:

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

I have the following script (below). which will return the status code of URLs. It loops through a file and tries to connect to each host. Only problem is that it obviously stops looping when it reaches an exception.

我已经尝试了无数次尝试将其操作方式循环,但无济于事.有什么想法吗?

I have tried numerous things to put the how of it in a loop, but to no avail. Any thoughts?

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

I've come up with this in the mean-time, any issues with this? (i'm still learning :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

您可以在引发异常的地方进行处理.另外,在打开文件时使用上下文管理器,这样可以简化代码.

You could handle the exception where it is raised. Also, use a context manager when opening files, it makes for simpler code.

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"