Evaluate my first python script, please

Pete Emerson pemerson at gmail.com
Fri Mar 5 00:59:58 CET 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
		hostname = line.strip().split('\t')[2]			# The host I want is always
at the 3rd tab.
	except IndexError:
	if hostname.startswith('float.') or
	if search_terms <= set(hostname.split('.')):      # same as if

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

More information about the Python-list mailing list