Python:出现异常后继续循环 [英] Python: Continue looping after exception

查看:129
本文介绍了Python:出现异常后继续循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下脚本(如下).它将返回URL的状态码.它遍历文件并尝试连接到每个主机.唯一的问题是,当到达异常时,它显然会停止循环.

I have the following script (below). which will return the status code of URLs. It loops through a file and tries to connect to each host. Only problem is that it obviously stops looping when it reaches an exception.

我已经尝试了无数次尝试将其操作方式循环,但无济于事.有什么想法吗?

I have tried numerous things to put the how of it in a loop, but to no avail. Any thoughts?

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)...

I've come up with this in the mean-time, any issues with this? (i'm still learning :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

推荐答案

您可以在引发异常的地方进行处理.另外,在打开文件时使用上下文管理器,这样可以简化代码.

You could handle the exception where it is raised. Also, use a context manager when opening files, it makes for simpler code.

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"

这篇关于Python:出现异常后继续循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆