Posted By

xzkcz on 01/04/10


Tagged

parser config


Versions (?)

ConfigParser


 / Published in: Python
 

File: config.ini

[concurrent] processor = 20 thread = 10

[db] dbuser = root dbhost = 127.0.0.1 dbpass = zhaowei dbport = 3306

  1. #-*- encoding: gb2312 -*-
  2. import ConfigParser
  3. cf = ConfigParser.ConfigParser()
  4. cf.read("config.ini")
  5. s = cf.sections()
  6. print 'section:', s
  7. o = cf.options("db")
  8. print 'options:', o
  9.  
  10. v = cf.items("db")
  11. print 'db:', v
  12.  
  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.  
  23. print "db_host:", db_host
  24. print "db_port:", db_port
  25. print "db_user:", db_user
  26. print "db_pass:", db_pass
  27. print "thread:", threads
  28. print "processor:", processors
  29. #修改一个值,再写回去
  30. cf.set("db", "db_pass", "zhaowei")
  31. cf.write(open("test.conf", "w"))

Report this snippet  

You need to login to post a comment.