gpt4 book ai didi

python - except 之后如何继续

转载 作者:太空宇宙 更新时间:2023-11-03 21:29:30 25 4
gpt4 key购买 nike

我有一个将主机名转换为 IP 的脚本。然而,当它发现一个不存在的东西时,它就会停止。我希望它继续下去,即使有一个异常(exception),但我找不到我的路。

#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

关于python - except 之后如何继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53611678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com