2012-02-07 81 views
1

我今天嘗試寫一個小python腳本,但已經失敗了。爲什麼下面的代碼在從shell調用後給了我下面的錯誤?簡單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控制檯和它的工作如預期。我的代碼有錯誤嗎?或者這是我的配置問題?

謝謝。

回答

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

我沒有在我的輸入文件中的空行,但我的問題仍然得到了通過使用你的建議:)固定。好奇爲什麼那是。無論如何,謝謝! – Julian 2012-02-07 22:49:44

+0

不要忘記文件中的最後一行。有時它在你的文本編輯器中不能很好地顯示出來。這可能是。 – secretmike 2012-02-07 22:53:42

1

可能問題在於line不包含預期值。要確保您可以在發生故障的行之前添加print line語句或使用pdb來調試程序。