我有以下脚本(如下)。这将返回URL的状态码。它通过文件循环并尝试连接到每个主机。唯一的问题是它在达到异常时显然停止循环。Python:异常后继续循环
我已经尝试了很多事情来把它如何在循环中,但无济于事。有什么想法吗?
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块捕获异常,然后警告并继续? –
@亚历克斯威尔逊,我又玩了一次......并改变了我的问题......这是你的意思吗? – MHibbin
确实如此。做得很好... –