在程序中使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在Python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是ConfigParser, Python ConfigParser模块解析的配置文件的格式比较象ini的配置文件格式
下面用实例说明如下:
配置文件db.conf
[db]
db_host=10.1.10.15
db_port=3306
db_user=root
db_pass=59222999
连接数据程序如下:
#!/usr/bin/env python
# coding:utf8
#author: [email protected]
import ConfigParser,string,os,sys
import MySQLdb
dbconf = ConfigParser.ConfigParser()
dbconf.read("db.conf")
#return section
s = dbconf.sections()
print s,‘\n‘
o = dbconf.options(‘db‘)
print ‘option:‘,o,‘\n‘
v = dbconf.items("db")
print ‘db:‘,v,‘\n‘
#可以按照类型读取出来
db_host = dbconf.get("db","db_host")
db_port = dbconf.get("db",‘db_port‘)
db_user = dbconf.get(‘db‘,‘db_user‘)
db_pass = dbconf.get(‘db‘,‘db_pass‘)
print db_host,db_port,db_user,db_pass,
#connect
conn = MySQLdb.connect(host = db_host,user = db_user,passwd = db_pass, port = int(db_port),db = ‘myapp‘)
cursor = conn.cursor()
#select tables
t = cursor.execute(‘‘‘show tables‘‘‘)
for tr in cursor.fetchall():
print tr,
#select tables result
n = cursor.execute(‘select * from auth_user‘)
for rr in cursor.fetchall():
print rr,
conn.close()
时间: 2024-11-09 00:22:57