繁体   English   中英

除后如何继续

[英]How to continue after 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,直到出现错误为止。 异常转换左行后如何继续?

谢谢

#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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM