Python读取ini配置文件


需求:

写个项目,用到数据库,多个地方使用,不能硬编码。很类似java的properties文件

Python支持ini文件的读取

涉及模块:

ConfigParser

xml文件

 
  1. db_config.ini  
  2. [baseconf]  
  3. host=127.0.0.1  
  4. port=3306  
  5. user=root  
  6. password=root  
  7. db_name=evaluting_sys  
  8. [concurrent]  
  9. processor=20  

对应的python代码

 
  1. #!/usr/bin/python   
  2. # -*- coding:utf-8 -*-   
  3. #author: lingyue.wkl   
  4. #desc: use to db ops   
  5. #---------------------   
  6. #2012-02-18 created   
  7.   
  8. #---------------------   
  9. import sys,os  
  10. import ConfigParser  
  11.   
  12. class Db_Connector:  
  13.   def __init__(self, config_file_path):  
  14.     cf = ConfigParser.ConfigParser()  
  15.     cf.read(config_file_path)  
  16.   
  17.     s = cf.sections()  
  18.     print 'section:', s  
  19.   
  20.     o = cf.options("baseconf")  
  21.     print 'options:', o  
  22.   
  23.     v = cf.items("baseconf")  
  24.     print 'db:', v  
  25.   
  26.     db_host = cf.get("baseconf""host")  
  27.     db_port = cf.getint("baseconf""port")  
  28.     db_user = cf.get("baseconf""user")  
  29.     db_pwd = cf.get("baseconf""password")  
  30.   
  31.     print db_host, db_port, db_user, db_pwd  
  32.   
  33.     cf.set("baseconf""db_pass""123456")  
  34.     cf.write(open("config_file_path""w"))  
  35. if __name__ == "__main__":  
  36.   f = Db_Connector("../conf/db_config.ini")  

得到结果:

section: ['concurrent', 'baseconf']
options: ['host', 'db_name', 'user', 'password', 'port']
db: [('host', '127.0.0.1'), ('db_name', 'evaluting_sys'), ('user', 'root'), ('password', 'root'), ('port', '3306')]
127.0.0.1 3306 root root

相关内容