Reading query parameters from textfile
I want to store the parameters for a mysql-connect in a textfile but do not know, what could be the most elegant 开发者_C百科way to store them in "query.txt" The readline() command seemed to be an option but somehow makes thing very inelegant. Can somebody suggest a smooth solution? thanks!
open("query.txt")
??? read parameters host, user, pass, db from query.txt ???
???sql = MySQLdb.connect (host = "%s", user = "%s", passwd = "%s", db = "s%"), host, user, pass, db)
This line causes me headache as well. I haven't figured out yet how to correctly make this query....
Yet another way: let's say you have a text file, params.txt
, that contains Python-style dictionary literal that has your parameters. It might look like this:
# my cool SQL parameters { "user": "lilu", "passwd": "multipass", "host": "woo.foo.baz", "db": "human-resources" }
You can use a safe and standard Python literals parser ast.literal_eval
to convert the contents of this file into a dictionary object, which you can then pass on to your SQL connection function.
import ast
defaults = dict(host='default-host-name', user='default-user-name')
# "U" mode is used so that no matter what newline styles you have in the file,
# they all become \n in memory.
with open('params.txt', 'rU') as params_fo:
params = dict(defaults)
params.update(ast.literal_eval(params_fo.read()))
sql = MySQLdb.connect(**params)
It will better and more confortable for you to use a serialization:
import cPickle
with open('pickler file.pic','w') as f:
host, user, passw, db = 'bouloudou','bididi',198754,'the_db'
cPickle.dump([host, user, passw, db],f)
with open('pickler file.pic','r') as f:
host, user, passw, db = cPickle.load(f)
Assuming that "query.txt' contains :
hostname username password db
you can do :
host, user, pass, db = open('query.txt').read().split()
sql = MySQLdb.connect (host = "%s", user = "%s", passwd = "%s", db = "s%"), host, user, pass, db)
You can use JSON if you want a text file that's both nicely-formatted and easy to read:
# Query parameters class
class QueryParams:
def __init__(self, paramsDict):
self.__dict__.update(paramsDict)
# Read text file
q = json.load(open('query.txt'), object_hook = lambda dc: QueryParams(dc))
# Use params
sql = MySQLdb.connect (host = "%s", user = "%s", passwd = "%s", db = "s%"), q.host, q.user, q.pass, q.db)
parameters.txt containing
MyHost, MyUsername, MyPassword, MyDb
In the script:
host, user, passw, db = open('parameters.txt').read().split()
sql = MySQLdb.connect (host , user, passw, db)
精彩评论