##
# copyright 2009, James William Pye
# http://python.projects.postgresql.org
##
'Parse pgpass files and subsequently lookup a password.'
import os
import csv

def parse(data):
	'produce a list of [(word, (host,port,dbname,user))] from a pgpass file object'
	return [
		(x[-1], x[0:4])
		for x in csv.reader(data,
			delimiter = ':',
			escapechar = '\\',
			quotechar = '\x00',
			doublequote = False,
			skipinitialspace = False,
			lineterminator = os.linesep,
			quoting = csv.QUOTE_NONE,
		) if x and not x[0].startswith('#')
	]

def lookup_password(words, uhpd):
	"""lookup_password(words, (user, host, port, database)) -> password

	Where 'words' is the output from pgpass.parse()
	"""
	user, host, port, database = uhpd
	for word, (w_host, w_port, w_database, w_user) in words:
		if (w_user == '*' or w_user == user) and \
			(w_host == '*' or w_host == host) and \
			(w_port == '*' or w_port == port) and \
		(w_database == '*' or w_database == database):
			return word

def lookup_password_file(path, t):
	'like lookup_password, but takes a file path'
	f = open(path)
	try:
		return lookup_password(parse(f), t)
	finally:
		f.close()

def lookup_pgpass(d, passfile):
	# If the password file exists, lookup the password
	# using the config's criteria.
	if os.path.exists(passfile):
		return lookup_password_file(passfile, (
			d['user'], d['host'], d['port'],
			d.get('database', d['user'])
		))

@@ -567,16 +567,18 @@
 d):%0A%09%22%22%22
+%0A%09
 lookup_p
@@ -1065,11 +1065,12 @@
 h'%0A%09
-f =
+with
  ope
@@ -1080,13 +1080,13 @@
 ath)
-%0A%09try
+ as f
 :%0A%09%09
@@ -1124,30 +1124,8 @@
 , t)
-%0A%09finally:%0A%09%09f.close()
 %0A%0Ade

Use with statement.