首页 > 解决方案 > sockect.gethostbyaddr 在从文件读取的 for 循环中

问题描述

尝试通过 socket.gethostbyaddr 提供文本文件列表,我似乎陷入了数据类型问题。

当尝试遍历列表时,除了最后一个测试行上的异常错误外,我没有得到任何输出

这只是一个小脚本,用于将 ip 解析为名称(如果存在)。测试我打开的文件只是:

1.1.1.1
2.2.2.2
10.1.1.1

我的本地主机在前两行中有一个“test1”或“test2”名称的条目

只是运行 socket.gethostbyaddr('1.1.1.1') 将“test1”作为主机返回,所以我知道该部分对于测试是正确的

import subprocess
import socket
tstout = open('testout.txt','w+')
with open("testip.txt", "r") as ins:
    for l in ins:
        line = str(l)
    try:
        tstout.write (socket.gethostbyaddr(line))
    except Exception as e:
        print (e)
tstout.close()
subprocess.Popen([r'c:\Windows\notepad.exe',r'c:\scripts\testout.txt'])

期望输出文件将解析结果写入其中,感谢我搞砸的任何指针

简化为:

import socket
tstout = open('testout.txt','w+')
with open("testip.txt", "r") as ins:
    for l in ins:
        l = str(l)
#        print(l)
        tstout.write (socket.gethostbyaddr(l))

标签: pythonpython-3.x

解决方案


推荐阅读