improve your python code(11)__python

來源:互聯網
上載者:User

ini設定檔 深入掌握ConfigParser

1. ini設定檔

如果我們程式沒有任何設定檔時,這樣的程式對外是全封閉的,一旦程式需要修改一些參數必須要修改程式碼本身並重新編譯,這樣很不好,所以要用設定檔,讓程式出廠後還能根據需要進行必要的配置;設定檔有很多如INI設定檔,XML設定檔,還有就是可以使用系統註冊表等。在早期的windows案頭系統中主要是用INI檔案作為系統的設定檔,從win95以後開始轉向使用註冊表,但是還有很多系統配置是使用INI檔案的。其實INI檔案就是簡單的text檔案,只不過這種txt檔案要遵循一定的INI檔案格式。“.INI ”就是英文 “initialization”的頭三個字母的縮寫;當然INI file的尾碼名也不一定是”.ini”也可以是”.cfg”,”.conf ”或者是”.txt”。

經典格式:

INI檔案的格式很簡單,最基本的三個要素是:parameters,sections和comments。

什麼是parameters。

INI所包含的最基本的“元素”就是parameter;每一個parameter都有一個name和一個value,name和value是由等號“=”隔開。name在等號的左邊。

如:

name = value

什麼是sections 。

所有的parameters都是以sections為單位結合在一起的。所有的section名稱都是獨佔一行,並且sections名字都被方括弧包圍著([ and ])。在section聲明後的所有parameters都是屬於該section。對於一個section沒有明顯的結束標誌符,一個section的開始就是上一個section的結束,或者是end of the file。Sections一般情況下不能被nested,當然特殊情況下也可以實現sections的嵌套。

section如下所示:

[section]

什麼是comments 。

在INI檔案中備註陳述式是以分號“;”開始的。所有的所有的備註陳述式不管多長都是獨佔一行直到結束的。在分號和行結束符之間的所有內容都是被忽略的。

注釋執行個體如下:

;comments text

INI執行個體:

;db_config.conf[baseconf]host=localhostuser=rootpassword=rootdb=your_db_nameuse_unicode=Truecharset=utf8[concurrent]processor=20
2. 深入掌握ConfigParser

configparser 模組能被用來讀取設定檔。例如,假設你有如下的設定檔:

; config.ini; Sample configuration file[installation]library=%(prefix)s/libinclude=%(prefix)s/includebin=%(prefix)s/binprefix=/usr/local# Setting related to debug configuration[debug]log_errors=trueshow_warnings=False[server]port: 8080nworkers: 32pid-file=/tmp/spam.pidroot=/www/rootsignature:=================================Brought to you by the Python Cookbook=================================

下面是一個讀取和提取其中值的例子:

> > > from configparser import ConfigParser> > > cfg = ConfigParser()> > > cfg.read('config.ini')> > > ['config.ini']> > > cfg.sections()> > > ['installation', 'debug', 'server']> > > cfg.get('installation','library')> > > '/usr/local/lib'> > > cfg.getboolean('debug','log_errors')True> > > cfg.getint('server','port')> > > 8080> > > cfg.getint('server','nworkers')> > > 32> > > print(cfg.get('server','signature'))\=================================Brought to you by the Python Cookbook\=================================

如果有需要,你還能修改配置並使用 cfg.write() 方法將其寫回到檔案中。例如:

cfg.set('server','port','9000')cfg.set('debug','log_errors','False')import syscfg.write(sys.stdout)[installation]library = %(prefix)s/libinclude = %(prefix)s/includebin = %(prefix)s/binprefix = /usr/local
[debug]log_errors = Falseshow_warnings = False[server]port = 9000nworkers = 32pid-file = /tmp/spam.pidroot = /www/rootsignature =      =================================      Brought to you by the Python Cookbook      =================================

討論
設定檔作為一種可讀性很好的格式,非常適用於儲存程式中的配置資料。 在每個設定檔中,配置資料會被分組(比如例子中的“installation”、 “debug” 和 “server”)。 每個分組在其中指定對應的各個變數值。

對於可實現同樣功能的設定檔和Python源檔案是有很大的不同的。 首先,設定檔的文法要更自由些,下面的指派陳述式是等效的:

prefix=/usr/local
prefix: /usr/local
設定檔中的名字是不區分大小寫。例如:

cfg.get('installation','PREFIX')
'/usr/local'
cfg.get('installation','prefix')
'/usr/local'

在解析值的時候,getboolean() 方法尋找任何可行的值。例如下面都是等價的:

log_errors = true
log_errors = TRUE
log_errors = Yes
log_errors = 1
或許設定檔和Python代碼最大的不同在於,它並不是從上而下的順序執行。 檔案是安裝一個整體被讀取的。如果碰到了變數替換,它實際上已經被替換完成了。 例如,在下面這個配置中,prefix 變數在使用它的變數之前或之後定義都是可以的:

[installation]
library=%(prefix)s/lib
include=%(prefix)s/include
bin=%(prefix)s/bin
prefix=/usr/local
ConfigParser 有個容易被忽視的特性是它能一次讀取多個設定檔然後合并成一個配置。 例如,假設一個使用者像下面這樣構造了他們的設定檔:

; ~/.config.ini
[installation]
prefix=/Users/beazley/test

[debug]
log_errors=False
讀取這個檔案,它就能跟之前的配置合并起來。如:

> > > # Previously read configuration> > >> > > cfg.get('installation', 'prefix')> > > '/usr/local'> > > # Merge in user-specific configuration> > >> > > import os> > > cfg.read(os.path.expanduser('~/.config.ini'))> > > ['/Users/beazley/.config.ini']> > > cfg.get('installation', 'prefix')> > > '/Users/beazley/test'> > > cfg.get('installation', 'library')> > > '/Users/beazley/test/lib'> > > cfg.getboolean('debug', 'log_errors')> > > False

仔細觀察下 prefix 變數是怎樣覆蓋其他相關變數的,比如 library 的設定值。 產生這種結果的原因是變數的改寫採取的是後發制人策略,以最後一個為準。 你可以像下面這樣做實驗:

> > > cfg.get('installation','library')> > > '/Users/beazley/test/lib'> > > cfg.set('installation','prefix','/tmp/dir')> > > cfg.get('installation','library')> > > '/tmp/dir/lib'

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.