user2820987
user2820987

Reputation: 55

python - print output

I have created this below script and it works fine. But the output is not friendly (see below). I want the first line to display only the hostname and IP and remove (,'[], please suggest

('testhostname', [], ['10.10.10.10'])
cannot resolve hostname:  10.10.10.11

import socket
pfile = open ('C:\\Python27\\scripts\\test.txt')
while True:
    IP = pfile.readline()
    if not IP:
        break
    try:
        host = socket.gethostbyaddr(IP.rstrip())
        print host
    except socket.herror, err:
        print "cannot resolve hostname: ", IP
pfile.close()

Upvotes: 0

Views: 135

Answers (1)

Blckknght
Blckknght

Reputation: 104712

Rather than printing all of the host tuple that is returned by gethostbyaddr, I suggest unpacking into separate variables that you can then print as you see fit:

hostname, alias_list, ip_addr_list = gethostbyaddr(IP.rstrip())
print hostname, ip_addr_list # or ip_addr_list[0] if you only want the one IP

If you want more control over the formatting, I suggest using the str.format method:

print "hostname: {}, IP(s): {}".format(hostname, ", ".join(ip_addr_list))

Also, a few other code suggestions (not directly related to your main question):

  • Use a with statement rather than manually opening and closing your file.
  • Iterate on the file object directly (with for IP in pfile:), rather than using while True: and calling pfile.readline() each time through.
  • Use the syntax except socek.herror as err rather than the older form with commas (which is deprecated in Python 2 and no longer exists in Python 3).

Upvotes: 4

Related Questions