標籤:
在程式中使用設定檔來靈活的配置一些參數是一件很常見的事情,設定檔的解析並不複雜,在Python裡更是如此,在官方發布的庫中就包含有做這件事情的庫,那就是ConfigParser, Python ConfigParser模組解析的設定檔的格式比較象ini的設定檔格式
下面用執行個體說明如下:
設定檔db.conf
[db]db_host=10.1.10.15db_port=3306db_user=rootdb_pass=59222999
串連資料程式如下:
#!/usr/bin/env python# coding:utf8#author: [email protected]import ConfigParser,string,os,sysimport MySQLdbdbconf = ConfigParser.ConfigParser()dbconf.read("db.conf")#return sections = 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,#connectconn = MySQLdb.connect(host = db_host,user = db_user,passwd = db_pass, port = int(db_port),db = ‘myapp‘)cursor = conn.cursor()#select tablest = cursor.execute(‘‘‘show tables‘‘‘)for tr in cursor.fetchall(): print tr,#select tables resultn = cursor.execute(‘select * from auth_user‘)for rr in cursor.fetchall(): print rr,conn.close()
python 常用模組之ConfigParser