我有以下腳本(如下)。這將返回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
確實如此。做得很好... –