【发布时间】:2012-07-03 08:12:59
【问题描述】:
我有以下脚本(如下)。这将返回 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
【问题讨论】:
-
您是否尝试过使用 try...except 块捕获异常,然后发出警告并继续?
-
@Alex Wilson,我又玩了一个游戏……然后改变了我的问题……这是你的意思吗?