python模組之ConfigParser ini

來源:互聯網
上載者:User

轉載自:http://hi.baidu.com/myitlyj/blog/item/25586bd7088ba3dba044df6b.html<br />在程式中使用設定檔來靈活的配置一些參數是一件很常見的事情,設定檔的解析並不複雜,在python裡更是如此,在官方發布的庫中就包含有做這件事情的庫,那就是ConfigParser,這裡簡單的做一些介紹。<br /> ConfigParser解析的設定檔的格式比較象ini的設定檔格式,就是檔案中由多個section構成,每個section下又有多個配置項,比如:<br />[db]<br />db_host=127.0.0.1<br />db_port=3306<br />db_user=root<br />db_pass=password<br />[concurrent]<br />thread=10<br />processor=20<br /> 假設上面的設定檔的名字為test.conf。裡麵包含兩個section,一個是db, 另一個是concurrent, db裡面還包含有4項,concurrent裡面有兩項。這裡來做做解析:<br />#-*- encoding: gb2312 -*-<br />import ConfigParser<br />import string, os, sys<br />cf = ConfigParser.ConfigParser()<br />cf.read("test.conf")<br /># 返回所有的section<br />s = cf.sections()<br />print 'section:', s<br />o = cf.options("db")<br />print 'options:', o<br />v = cf.items("db")<br />print 'db:', v<br />print '-'*60<br />#可以按照類型讀取出來<br />db_host = cf.get("db", "db_host")<br />db_port = cf.getint("db", "db_port")<br />db_user = cf.get("db", "db_user")<br />db_pass = cf.get("db", "db_pass")<br /># 返回的是整型的<br />threads = cf.getint("concurrent", "thread")<br />processors = cf.getint("concurrent", "processor")<br />print "db_host:", db_host<br />print "db_port:", db_port<br />print "db_user:", db_user<br />print "db_pass:", db_pass<br />print "thread:", threads<br />print "processor:", processors<br />#修改一個值,再寫回去<br />cf.set("db", "db_pass", "zhaowei")<br />cf.write(open("test.conf", "w"))<br />

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.