self-confidence,the source of all the power

导航

python configparse

在程序中使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在Python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是ConfigParser,这里简单的做一些介绍。

Python ConfigParser模块解析的配置文件的格式比较象ini的配置文件格式,就是文件中由多个section构成,每个section下又有多个配置项,比如:

  1. [db]  
  2. db_host=127.0.0.1  
  3. db_port=3306 
  4. db_user=root 
  5. db_pass=password 
  6. [concurrent]  
  7. thread=10 
  8. processor=20 

假设上面的配置文件的名字为test.conf。里面包含两个section,一个是db, 另一个是concurrent, db里面还包含有4项,concurrent里面有两项。这里来做做解析:

  1. #-*- encoding: gb2312 -*-  
  2. import ConfigParser  
  3. import string, os, sys  
  4. cf = ConfigParser.ConfigParser()  
  5. cf.read("test.conf")  
  6. # 返回所有的section  
  7. s = cf.sections()  
  8. print 'section:', s  
  9. o = cf.options("db")  
  10. print 'options:', o  
  11. v = cf.items("db")  
  12. print 'db:', v  
  13. print '-'*60  
  14. #可以按照类型读取出来  
  15. db_host = cf.get("db", "db_host")  
  16. db_port = cf.getint("db", "db_port")  
  17. db_user = cf.get("db", "db_user")  
  18. db_pass = cf.get("db", "db_pass")  
  19. # 返回的是整型的  
  20. threads = cf.getint("concurrent", "thread")  
  21. processors = cf.getint("concurrent", "processor")  
  22. print "db_host:", db_host  
  23. print "db_port:", db_port  
  24. print "db_user:", db_user  
  25. print "db_pass:", db_pass  
  26. print "thread:", threads  
  27. print "processor:", processors  
  28. #修改一个值,再写回去  
  29. cf.set("db", "db_pass", "zhaowei")  
  30. cf.write(open("test.conf", "w")) 

posted on 2012-10-10 14:22  漩涡鸣人  阅读(436)  评论(0编辑  收藏  举报