【问题标题】:Error in simple python module简单的python模块中的错误
【发布时间】:2012-02-07 22:36:38
【问题描述】:

我今天尝试编写一个小 Python 脚本,但失败了。为什么下面的代码被shell调用后出现如下错误?

错误

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-console 中测试了 socket 模块,它按预期工作。是我的代码有错误还是我的配置有问题?

谢谢。

【问题讨论】:

    标签: python shell


    【解决方案1】:

    您的输入文件中可能有一个空行。尝试在 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')
    

    【讨论】:

    • 我的输入文件中没有空行,但是通过使用您的建议解决了我的问题:)。很好奇为什么会这样。无论如何,谢谢!
    • 不要忘记文件中的最后一行。有时它不会在您的文本编辑器中很好地显示出来。可能就是这样。
    【解决方案2】:

    问题可能在于line 不包含预期值。为了确保这一点,您可以在失败的行之前添加 print line 语句或使用 pdb 来调试程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-08
      • 1970-01-01
      • 1970-01-01
      • 2017-06-10
      • 2016-05-16
      • 1970-01-01
      • 2019-09-02
      相关资源
      最近更新 更多