ConfigParser
生活随笔
收集整理的這篇文章主要介紹了
ConfigParser
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
FROM: http://blog.chinaunix.net/uid-25890465-id-3312861.html
一、ConfigParser簡介
ConfigParser 是用來讀取配置文件的包。配置文件的格式如下:中括號“[ ]”內包含的為section。section 下面為類似于key-value 的配置內容。
1: [db] 2: db_host = 127.0.0.1 3: db_port = 22 4: db_user = root 5: db_pass = rootroot 6:? 7: [concurrent] 8: thread = 10 9: processor = 20中括號“[ ]”內包含的為section。緊接著section 為類似于key-value 的options 的配置內容。
?
二、ConfigParser 初始工作使用ConfigParser 首選需要初始化實例,并讀取配置文件:
1: cf = ConfigParser.ConfigParser() 2: cf.read("配置文件名")?
三、ConfigParser 常用方法1. 獲取所有sections。也就是將配置文件中所有“[ ]”讀取到列表中:
1: s = cf.sections() 2: print 'section:', s將輸出(以下將均以簡介中配置文件為例):
1: section: ['db', 'concurrent']2. 獲取指定section 的options。即將配置文件某個section 內key 讀取到列表中:
1: o = cf.options("db") 2: print 'options:', o將輸出:
1: options: ['db_host', 'db_port', 'db_user', 'db_pass']3. 獲取指定section 的配置信息。
1: v = cf.items("db") 2: print 'db:', v將輸出:
1: db: [('db_host', '127.0.0.1'), ('db_port', '22'), ('db_user', 'root'), ('db_pass', 'rootroot')]4. 按照類型讀取指定section 的option 信息。
同樣的還有getfloat、getboolean。
1: #可以按照類型讀取出來 2: db_host = cf.get("db", "db_host") 3: db_port = cf.getint("db", "db_port") 4: db_user = cf.get("db", "db_user") 5: db_pass = cf.get("db", "db_pass") 6:? 7: # 返回的是整型的 8: threads = cf.getint("concurrent", "thread") 9: processors = cf.getint("concurrent", "processor") 10:? 11: print "db_host:", db_host 12: print "db_port:", db_port 13: print "db_user:", db_user 14: print "db_pass:", db_pass 15: print "thread:", threads 16: print "processor:", processors將輸出:
1: db_host: 127.0.0.1 2: db_port: 22 3: db_user: root 4: db_pass: rootroot 5: thread: 10 6: processor: 205. 設置某個option 的值。(記得最后要寫回)
1: cf.set("db", "db_pass", "zhaowei") 2: cf.write(open("test.conf", "w"))6.添加一個section。(同樣要寫回)
1: cf.add_section('liuqing') 2: cf.set('liuqing', 'int', '15') 3: cf.set('liuqing', 'bool', 'true') 4: cf.set('liuqing', 'float', '3.1415') 5: cf.set('liuqing', 'baz', 'fun') 6: cf.set('liuqing', 'bar', 'Python') 7: cf.set('liuqing', 'foo', '%(bar)s is %(baz)s!') 8: cf.write(open("test.conf", "w"))7. 移除section 或者option 。(只要進行了修改就要寫回的哦)
1: cf.remove_option('liuqing','int') 2: cf.remove_section('liuqing') 3: cf.write(open( "test.conf", "w"))點擊(此處)折疊或打開
總結
以上是生活随笔為你收集整理的ConfigParser的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Gearman的使用
- 下一篇: wsgi初探