1

我有这个将主机名转换为 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,直到出现错误。异常转换左行后如何继续?

谢谢

4

1 回答 1

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

Note that your other function would raise an exception if the file is empty. Also you don't need to iterate over the file. use readlines() method of file object to read all lines in a list then just return len of this list.

于 2018-12-04T11:31:13.147 回答