2010-08-27 34 views
6

如何在python configparser模塊的ini文件中解析沒有值的標籤?如何使用ConfigParser處理配置文件中的空值?

例如,我有以下ini,我需要解析rb。在一些ini文件中,rb具有整數值,在一些沒有值的情況下,就像下面的例子。我怎樣才能用configparser做到這一點,而不會得到一個值的錯誤?我用調用getInt功能

[section] 
person=name 
id=000 
rb= 
+4

請使用標點符號。 – Seth 2010-08-27 18:24:49

回答

6

也許使用try...except塊:

try: 
     value=parser.getint(section,option) 
    except ValueError: 
     value=parser.get(section,option) 

例如:

import ConfigParser 

filename='config' 
parser=ConfigParser.SafeConfigParser() 
parser.read([filename]) 
print(parser.sections()) 
# ['section'] 
for section in parser.sections(): 
    print(parser.options(section)) 
    # ['id', 'rb', 'person'] 
    for option in parser.options(section): 
     try: 
      value=parser.getint(section,option) 
     except ValueError: 
      value=parser.get(section,option) 
     print(option,value,type(value)) 
     # ('id', 0, <type 'int'>) 
     # ('rb', '', <type 'str'>) 
     # ('person', 'name', <type 'str'>) 
print(parser.items('section')) 
# [('id', '000'), ('rb', ''), ('person', 'name')] 
+0

它是我的python版本中的ConfigParser.NoOptionError。 – 2012-10-08 14:10:34

11

您需要在創建解析器對象時設置allow_no_value=True可選參數。

+0

我試圖用 配置= ConfigParser.ConfigParser(allow_no_value = TRUE) config.read(infFile) ,但我得到這個錯誤 類型錯誤:__init __()得到了一個意想不到的關鍵字參數「allow_no_value – AKM 2010-08-27 18:36:25

+3

貌似是[參數] (http://docs.python.org/library/configparser.html#ConfigParser.RawConfigParser)僅在Python 2.7中添加。 – Santa 2010-08-27 20:10:18

+2

然後問題代表如何用2.6的ConfigParser處理空值。 – Exploring 2013-12-11 22:35:19

3

而不是使用getint()的,使用get()拿到選項作爲一個字符串。然後轉換爲int自己:

rb = parser.get("section", "rb") 
if rb: 
    rb = int(rb) 
0

由於仍有約2.6蟒一個懸而未決的問題,下面就與Python 2.7或2.6的工作。這取代了用於解析ConfigParser中的選項,分隔符和值的內部正則表達式。

def rawConfigParserAllowNoValue(config): 
    '''This is a hack to support python 2.6. ConfigParser provides the 
    option allow_no_value=True to do this, but python 2.6 doesn't have it. 
    ''' 
    OPTCRE_NV = re.compile(
     r'(?P<option>[^:=\s][^:=]*)' # match "option" that doesn't start with white space 
     r'\s*'       # match optional white space 
     r'(?P<vi>(?:[:=]|\s*(?=$)))\s*' # match separator ("vi") (or white space if followed by end of string) 
     r'(?P<value>.*)$'    # match possibly empty "value" and end of string 
    ) 
    config.OPTCRE = OPTCRE_NV 
    config._optcre = OPTCRE_NV 
    return config 

用作

fp = open("myFile.conf") 
    config = ConfigParser.RawConfigParser() 
    config = rawConfigParserAllowNoValue(config) 

旁註

還有就是Python 2.7 ConfigParser一個OPTCRE_NV,但如果我們在上面的功能,用它準確地,正則表達式將返回None用於vi和value,這會導致ConfigParser在內部失敗。使用上面的函數爲vi和value返回一個空字符串,並且每個人都很高興。

相關問題