简单Python模块中的错误

1 投票
2 回答
626 浏览
提问于 2025-04-17 12:32

我今天尝试写一个简单的Python脚本,但结果非常糟糕。为什么我在命令行调用下面的代码时会出现以下错误呢?

错误信息

File "./testmod.py", line 15, in <module>
    printdnsfile(sys.argv[1])
  File "./testmod.py", line 10, in printdnsfile
    print(socket.gethostbyname(str(line)))
socket.gaierror: [Errno 8] nodename nor servname provided, or not known

代码

#!/usr/bin/python

def printdnsfile(file):
    file= open (file,"r")
    import socket
    dest = open("/dnsfile.txt",'w')
    for line in file:
        print(socket.gethostbyname(str(line)))
        print>>dest, str(",".join([line,socket.gethostbyname(line)])+'\n')

if __name__ == "__main__":
    import sys
    printdnsfile(sys.argv[1]) 

我在Python控制台测试了socket模块,它的表现正常。请问是我的代码有问题,还是我的配置出了问题呢?

谢谢。

2 个回答

1

可能问题出在 line 里面没有你想要的值。为了确认这一点,你可以在出错的那一行之前加一个 print line 的语句,看看 line 里面到底是什么,或者使用 pdb 来调试程序。

2

你的输入文件里可能有空行。在调用gethostbyname之前,试着检查一下你的行。

def printdnsfile(file):
    file= open (file,"r")
    import socket
    dest = open("/dnsfile.txt",'w')
    for line in file:
        line = line.strip()
        if line:
            print(socket.gethostbyname(str(line)))
            print>>dest, str(",".join([line,socket.gethostbyname(line)])+'\n')

撰写回答