除后如何继续

时间:2018-12-04 11:12:56

标签: python try-catch except

我有这个脚本,可以将主机名转换为IP。但是,当找到一个不存在的对象时,它将停止。即使有例外,我希望它继续进行,但是我找不到自己的路。

#Script to resolve hostname to IP. Needs improving.
import socket

def file_len(fname):
    with open(fname) as f:
        for i, l in enumerate(f):
            pass
    return i + 1

def resolve_ip():

with open("test.txt", "r") as ins:
    try:
        for line in ins:
            print(socket.gethostbyname(line.strip()))

    except Exception:
            print(line)


resolve_ip()

主要是,这将打印所有IP,直到出现错误为止。异常转换左行后如何继续?

谢谢

1 个答案:

答案 0 :(得分:0)

#Script to resolve hostname to IP. Needs improving.
import socket

def resolve_ip(file_name):
    with open(file_name, "r") as ins:
        for line in ins:
            line = line.strip()
            try:
                print(socket.gethostbyname(line))
            except socket.gaierror:
                print(line)

resolve_ip('test.txt')

请注意,如果文件为空,则其他函数将引发异常。另外,您不需要遍历文件。使用文件对象的readlines()方法读取列表中的所有行,然后仅返回此列表的len