python ConfigParser模塊get方法簡介


ConfigParser模塊get官方文檔解釋如下:
The ConfigParser class extends some methods of the RawConfigParser interface, adding some optional arguments.

ConfigParser.get(section, option[, raw[, vars]])
Get an option value for the named section. If vars is provided, it must be a dictionary. The option is looked up in vars (if provided), section, and in defaults in that order.

All the '%' interpolations are expanded in the return values, unless the raw argument is true. Values for interpolation keys are looked up in the same manner as the option.

ConfigParser.items(section[, raw[, vars]])
Return a list of (name, value) pairs for each option in the given section. Optional arguments have the same meaning as for the get() method.

New in version 2.3.

簡單來說就是:獲取命名部分的選項值
ConfigParser.get(section,option [,raw [,vars]])
section 配置名
option 選項名
raw bool類型 可選參數,默認為False
vars dict類型 可選參數

如果提供了vars 那么獲取配置選項值得規則如下
先在vars中尋找,如果找到就使用vars中的值
如果找不到 就是用默認值
前提是raw的值是False

以下是測試代碼

文件test.conf內容如下

[Section1]
foo=%(bar)s is %(baz)s!
baz=fun
bar=Python

測試代碼:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import ConfigParser
import string, os
cf = ConfigParser.ConfigParser()
cf.read("test.conf")
res = cf.get('Section1', 'foo')
print "默認情況下, raw=False, 此時輸出 %s" % res
res = cf.get('Section1', 'foo', raw=False)
print "raw=False, 無參數vars 此時等同於默認輸出:%s" % res
res = cf.get('Section1', 'foo', raw=True)
print "raw=True, 無參數vars 此時等輸出未被匹配原字符:%s" % res
res = cf.get('Section1', 'foo', raw=False, vars={'bar': 'Documentation','baz': 'evil'})
print "raw=False, vars存在 此時使用vars中的值進行匹配:%s" % res
res = cf.get('Section1', 'foo', raw=True, vars={'bar': 'Documentation', 'baz':'sdsd'})
print "raw=True, vars存在 此時vars不生效,輸出未被匹配原字符:%s" % res
res = cf.get('Section1', 'foo', raw=False, vars={'bar': 'Documentation'})
print "raw=True, vars存在,但只包含一個值, 此時另一個值取默認匹配值,輸出未:%s" % res

輸出如下

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM