首页 > 编程语言 > 详细

python 常用模块之ConfigParser

时间:2015-06-25 00:01:28      阅读:332      评论:0      收藏:0      [点我收藏+]

在程序中使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在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: wangqiankun@lashou-inc.com


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()

python 常用模块之ConfigParser

原文:http://www.cnblogs.com/shantu/p/4598880.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!