Evaluate my first python script, please

Pete Emerson pemerson at gmail.com
Thu Mar 4 18:59:58 EST 2010


Great responses, thank you all very much. I read Jonathan Gardner's
solution first and investigated sets. It's clearly superior to my
first cut.

I love the comment about regular expressions. In perl, I've reached
for regexes WAY too much. That's a big lesson learned too, and from my
point of view not because of performance (although that's most likely
a bonus) but because of code readability.

Here's the version I have now. It looks quite similar to sjdevnull's.
Further comments appreciated, and thanks again.

#!/usr/bin/env python

import sys, fileinput, os

filename = '/etc/hosts'

hosts = []

search_terms = set(sys.argv[1:])

for line in open(filename, 'r'):
	if line.startswith('#'): continue
	try:
		hostname = line.strip().split('\t')[2]			# The host I want is always
at the 3rd tab.
	except IndexError:
		continue
	if hostname.startswith('float.') or
hostname.startswith('localhost.'):
		continue
	if search_terms <= set(hostname.split('.')):      # same as if
search_terms.issubset(hostname.split('.')):
		hosts.append(hostname)

if len(hosts) == 1:
	os.execl("/usr/bin/ssh", '-A', hosts[0])
else:
	for host in hosts:
		print host




More information about the Python-list mailing list