# demo.ini [DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no
上面的demo.ini是一個很是基礎的配置文件,它由多個部分(section)組成,每部分包含了帶值的選項。ConfigParse類的實例能夠對其進行讀寫操做。python
建立配置文件:app
import configparser config = configparser.ConfigParser() config["DEFAULT"] = {"ServerAliveInterval": "45", "Compression": "yes", "CompressionLevel": "9", "ForwardX11": "yes"} config["bitbucket.org"] = {} config["bitbucket.org"]["User"] = "hg" config['topsecret.server.com'] = {} topsecret = config['topsecret.server.com'] topsecret["Port"] = "50022" topsecret["ForwardX11"] = "no" with open("demo.ini", "w") as configfile: config.write(configfile)
對配置解析器的處理與字典相似。函數
讀取配置文件:this
>>> config = configparser.ConfigParser() >>> config.sections() [] >>> config.read("demo.ini") ["demo.ini"] >>> config.sections() ['bitbucket.org', 'topsecret.server.com'] >>> "bitbucket.org" in config True >>> "bitbong.com" in config False >>> config["bitbucket.org"]["User"] "hg" >>> config['DEFAULT']['Compression'] "yes" >>> topsecret = config['topsecret.server.com'] >>> topsecret['ForwardX11'] "no" >>> for key in config["bitbucket.org"]: ... print(key) user serveraliveinterval compression compressionlevel forwardx11 >>> config["bitbucket.org"]["ForwardX11"] "yes"
注意點:[DEFAULT]爲其餘全部section提供默認值,section中的全部鍵大小寫不敏感並以小寫字母存儲spa
配置解析器老是存儲配置的值爲字符串類型,所以用戶須要按需轉換爲指望的數據類型。因爲這種需求很是廣泛,配置解析器提供了一系列更簡便的方法來處理整數(getint()
)、浮點數(getfloat()
)及布爾值(getboolean()
)。用戶也能夠自行註冊轉換器或定製配置解析器已提供的轉換器。3d
>>> topsecret.getboolean('ForwardX11') False >>> config['bitbucket.org'].getboolean('ForwardX11') True >>> config.getboolean('bitbucket.org', 'Compression') True
注意點:getboolean()
方法對大小寫不敏感,能識別'yes'/'no', 'on'/'off', 'true'/'false'和'1'/'0'爲對應的布爾值代理
和字典同樣,可使用section的get()
方法提供後備值:code
>>> topsecret.get('CompressionLevel') '9' >>> topsecret.get('Cipher') >>> topsecret.get('Cipher', '3des-cbc') '3des-cbc
須要注意的是,默認值的優先級高於後備值。好比要想在'topsecret.server.com'中獲取'CompressionLevel'的值,即便指定了後備值,仍然獲得的是'DEFAULT'中的值:orm
>>> topsecret.get('CompressionLevel', '3') '9'
此外,除了section的get()
方法,還提供瞭解析器級別的get()
方法,支持向後兼容,後備值經過fallback
關鍵字指定:server
>>> config.get("bitbucket.org", "monster", fallback="No such things as monsters") "No such things as monsters"
fallback
關鍵字一樣支持在getint()
, getfloat()
和getboolean()
中使用
[section_name]
的形式打頭,後跟以特定字符(默認是=
或:
)分隔的鍵值對。#
和;
爲前綴。應該避免註解與鍵或值處在同一行,由於這將致使把註解視爲值的一部分。[Simple Values] key=value spaces in keys=allowed spaces in values=allowed as well spaces around the delimiter = obviously you can also use : to delimit keys from values [All Values Are Strings] values like this: 1000000 or this: 3.14159265359 are they treated as numbers? : no integers, floats and booleans are held as: strings can use the API to get converted values directly: true [Multiline Values] chorus: I'm a lumberjack, and I'm okay I sleep all night and I work all day [No Values] key_without_value empty string value here = [You can use comments] # like this ; or this # By default only in an empty line. # Inline comments can be harmful because they prevent users # from using the delimiting characters as parts of values. # That being said, this can be customized. [Sections Can Be Indented] can_values_be_as_well = True does_that_mean_anything_special = False purpose = formatting for readability multiline_values = are handled just fine as long as they are indented deeper than the first line of a value # Did I mention we can indent comments, too?
ConfigParser支持插值,調用get()
方法返回值以前將對值進行預處理
默認使用的Interpolation類。容許值包含格式化字符串,該字符串引用同一section中的值或DEFAULTSECT
section中的值。其餘默認值能夠在初始化時提供。
[Paths] home_dir: /Users my_dir: %(home_dir)s/lumberjack my_pictures: %(my_dir)s/Pictures
在上面的例子中,interpolation設置爲BasicInterpolation()
的ConfigParser將解析%(home_dir)s
爲home_dir
的值,%(my_dir)s
將解析爲/Users/lumberjack
。引用鏈中使用的鍵不須要在配置文件中以任何特定的順序指定。
若是interpolation設置爲None
,將直接返回%(home_dir)s/lumberjack
做爲my_dir
的值。
擴展的Interpolation類,實現了更高級的語法。它使用${section:option}
表示來自外部section的值,若是省去了section:
,默認指當前section(以及可能的DEFAULTSECT
section的值)
[Common] home_dir: /Users library_dir: /Library system_dir: /System macports_dir: /opt/local [Frameworks] Python: 3.2 path: ${Common:system_dir}/Library/Frameworks/ [Arthur] nickname: Two Sheds last_name: Jackson my_dir: ${Common:home_dir}/twosheds my_pictures: ${my_dir}/Pictures python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
映射協議訪問是容許像操做字典同樣使用自定義對象的功能的通用名稱。在configparser中,映射接口經過parser["section"]["option"]
的形式實現。
parser["section"]
返回解析器中section的值的代理,值從原始解析器中獲取但並不是經過複製的方式。在section代理上改變值的操做,其實是對原始解析器的改變。
configparser對象雖然表現的儘量接近字典,但仍有一些區別須要注意:
for option in parser["section"]
語句生成的option名稱老是被optionxform
函數轉換爲小寫。擁有"a"選項的section經過如下兩種方式訪問都將返回True:"a" in parser["section"] "A" in parser["section"]
DEFAULTSECT
的值,也就是說,對section的.clear()
操做可能並無真正的清空,這是由於沒法從該section刪除默認值。在除DEFAULTSECT
之外的section上刪除默認值(前提是沒有對默認值重寫)將拋出KeyError
異常>>> del topsecret["forwardx11"] >>> topsecret["forwardx11"] 'yes' >>> del topsecret["serveraliveinterval"] Traceback (most recent call last): ... raise KeyError(key) KeyError: 'serveraliveinterval'
DEFAULTSECT
不能從解析器移除
ValueError
異常parser.clear()
操做對它沒有任何影響parser.popitem()
不會返回DEFAULTSECT
>>> del config["DEFAULT"] Traceback (most recent call last): ... raise ValueError("Cannot remove the default section.") ValueError: Cannot remove the default section. >>> config.clear() >>> config["DEFAULT"]["serveraliveinterval"] '45'
parser.get(section, option, **kwargs)
- 第二個參數並不是字典的get()
方法表示的後備值,但section級別的get()
方法與映射協議倒是兼容的parser.items(raw=False, vars=None)
兼容映射協議(返回包含DEFAULTSECT
的(section_name, section_proxy)對的列表)。另有指定section的調用方式:parser.items(section, raw=False, vars=None)
.後者返回指定section的(option, value)對的列表,raw參數指定value中的格式化字符串是否插值表示>>> list(config.items()) [('DEFAULT', <Section: DEFAULT>), ('bitbucket.org', <Section: bitbucket.org>), ('topsecret.server.com', <Section: topsecret.server.com>)] >>> list(config.items("bitbucket.org")) [('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]
省略
省略
class configparser.ConfigParser(defaults=None, dict_type=dict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation(), converters={})
defaults()
返回包含實例範圍默認值的字典
sections()
返回可用section的名稱列表(不包含默認section的名稱)
add_section(section)
添加section。若是該section已經存在,拋出DuplicateSectionError
異常;若是傳入的是默認section的名稱,拋出ValueError
異常;若是傳入的參數不是字符串類型,拋出TypeError
異常
has_section(section)
判斷section是否存在。默認section老是返回False
options(section)
返回指定section的可用選項列表(包含DEFAULTSECT
中的選項)。指定默認section將拋出NoSectionError
異常
has_option(section, option)
若是section存在且包含指定的option,返回True,不然返回False。若是傳遞的section爲None
或""
,視爲默認section
read(filenames, encoding=None)
讀取並解析可迭代的文件名,返回成功解析的文件名列表
若是filenames是一個字符串,或字節對象又或者是類路徑對象,視其爲單個文件。若是filenames中的某個文件不能打開,該文件將被忽略
若是filenames中全部文件都不存在,ConfigParser實例將包含空數據集。若是某個應用須要導入初始化值,應該在調用read()導入可選配置文件前調用read_file()
讀取相應的初始化配置文件,由於read_file()
讀取不能打開的文件時會拋出FileNotFoundError
異常,而不會直接忽略
import configparser, os config = configparser.ConfigParser() config.read_file(open('defaults.cfg')) config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')], encoding='cp1250')
read_file(f, source=None)
從可迭代生成Unicode字符串的f(例如以文本模式打開的文件對象)讀取及解析配置數據
read_string(string, source='<string>')
從字符串中解析配置數據
read_dict(dictionary, source='<dict>')
從提供相似dict的items()方法的對象加載配置。key是section名稱,value是包含選項和值的字典。若是使用的字典類型支持保留順序,section及其選項將按序添加,全部值自動轉換爲字符串
get(section, option, * , raw=False, vars=None[, fallback])
獲取指定section的選項的值。vars參數做爲字典對象傳遞。option按照vars,section,DEFAULTSECT的順序進行查找,若是不存在且提供了fallback參數,返回fallback的值,fallback能夠是None
raw參數指定value中的格式化字符串是否插值表示,與option的查找順序相同
getint(section, option, * , raw=False, vars=None[, fallback])
轉換option的值爲int類型
getfloat(section, option, * , raw=False, vars=None[, fallback])
轉換option的值爲float類型
getboolean(section, option, * , raw=False, vars=None[, fallback])
轉換option的值爲bool類型
items(raw=False, vars=None)
items(section, raw=False, vars=None)
前者返回包含DEFAULTSECT
的(section_name, section_proxy)對的列表。後者返回指定section的(option, value)對的列表
set(section, option, value)
若是section存在,設置option的值爲value,不然拋出NoSectionError
異常。option和value必須是字符串類型,不然拋出TypeError
異常
write(fileobject, space_around_delimiters=True)
將ConfigParser對象寫入以文件模式打開的文件。
remove_option(section, option)
從section中移除指定的選項。若是section不存在,拋出NoSectionError
異常。若是option存在返回True,不然返回False
remove_section(section)
移除指定section。若是section存在返回True,不然返回False(對默認section的操做老是返回False)
optionxform(option)
對option的處理函數,默認返回option的小寫形式。能夠經過繼承重寫或設置ConfigParser實例的optionxform
屬性(接收一個字符串參數並返回一個新的字符串的函數)改變默認行爲。
cfgparser = ConfigParser() cfgparser.optionxform = str
讀取配置文件時,option兩邊的空格在調用此函數前先被移除
readfp(fp, filename=None)
已棄用,使用 read_file()
替代
configparser.MAX_INTERPOLATION_DEPTH
當raw參數爲false時,get()方法遞歸插值的最大深度。僅在使用默認的BasicInterpolation
時纔有意義
省略
省略