12

我有以下脚本(如下)。这将返回 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"

谢谢,

米宾

4

3 回答 3

15

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

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"
于 2012-07-03T08:21:21.500 回答
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()
于 2012-07-03T08:18:06.920 回答
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()
于 2012-07-03T09:00:03.797 回答