1

I tried to write a little python script today but have failed horribly. Why is it that the code below gives me the following error after being called from the shell?

Error

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

Code

#!/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]) 

I tested the socket module in the python-console and it worked as expected. Is there an error with my code or is this a problem with my configuration?

Thanks.

2 Answers 2

2

You might have an empty line in your input file. Try checking your line before you 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')
Sign up to request clarification or add additional context in comments.

2 Comments

I don't have an empty line in my input file, however my problem nevertheless got fixed by using your suggestion :). Curious why that is though. Anyway, Thank you!
Don't forget about the final line in the file. Sometimes it doesn't show up very well in your text editor. That could be it.
1

Probably the problem is that line doesn't contain the expected value. To make sure about that you could add a print line statement before the line that is failing or use pdb to debug the program.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.