Python:异常后继续循环

MHi*_*bin 10 python loops exception

我有以下脚本(下面).这将返回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()
Run Code Online (Sandbox Code Playgroud)

编辑:

我是在平均时间提出这个,有什么问题吗?(我还在学习: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"
Run Code Online (Sandbox Code Playgroud)

谢谢,

MHibbin

ayc*_*dee 12

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

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"
Run Code Online (Sandbox Code Playgroud)

  • `for line in f`在这里可能比while循环更好. (3认同)