Python 如何使用 ConfigParser 处理配置文件中的空值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3587041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:50:52  来源:igfitidea点击:

How to handle empty values in config files with ConfigParser?

pythonconfigparser

提问by AKM

How can I parse tags with no value in an ini file with python configparser module?

如何使用 python configparser 模块解析 ini 文件中没有值的标签?

For example, I have the following ini and I need to parse rb. In some ini files rb has integer values and on some no value at all like the example below. How can I do that with configparser without getting a valueerror? I use the getint function

例如,我有以下 ini,我需要解析 rb。在某些 ini 文件中,rb 具有整数值,而在某些情况下根本没有值,如下例所示。如何使用 configparser 做到这一点而不会出现 valueerror?我使用 getint 函数

[section]
person=name
id=000
rb=

采纳答案by unutbu

Maybe use a try...exceptblock:

也许使用一个try...except块:

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

For example:

例如:

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')]

回答by Santa

You need to set allow_no_value=Trueoptional argument when creating the parser object.

allow_no_value=True创建解析器对象时需要设置可选参数。

回答by Ned Batchelder

Instead of using getint(), use get()to get the option as a string. Then convert to an int yourself:

不是使用getint(),而是使用get()以字符串形式获取选项。然后自己转换为 int :

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

回答by ams

Since there is still an unanswered question about python 2.6, the following will work with python 2.7 or 2.6. This replaces the internal regex used to parse the option, separator, and value in ConfigParser.

由于仍然存在关于 python 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

Use as

用于

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

Side Note

边注

There is a OPTCRE_NV in ConfigParser for Python 2.7, but if we used it in the above function exactly, the regex would return None for vi and value, which causes ConfigParser to fail internally. Using the function above returns a blank string for vi and value and everyone is happy.

在 Python 2.7 的 ConfigParser 中有一个 OPTCRE_NV,但是如果我们在上面的函数中准确地使用它,正则表达式将为 vi 和 value 返回 None,这会导致 ConfigParser 在内部失败。使用上面的函数为 vi 和 value 返回一个空字符串,每个人都很高兴。