【问题标题】:How to handle empty values in config files with ConfigParser?如何使用 ConfigParser 处理配置文件中的空值?
【发布时间】:2010-08-27 18:21:30
【问题描述】:

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

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

[section]
person=name
id=000
rb=

【问题讨论】:

    标签: python configparser


    【解决方案1】:

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

    【讨论】:

    • 我尝试使用 config = ConfigParser.ConfigParser(allow_no_value=True) config.read(infFile) 但我收到此错误 TypeError: __init__() got an unexpected keyword argument 'allow_no_value
    • 看起来argument 是仅在 Python 2.7 中添加的。
    • 那么问题是如何使用 ConfigParser for 2.6 处理空值。
    • 如果= 仍然存在,allow_no_value=True 与空值无关,它与使用 getint 和空值的能力关系更小。
    【解决方案2】:

    也许使用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')]
    

    【讨论】:

    • 我的python版本是ConfigParser.NoOptionError。
    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      由于关于 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
      

      用作

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

      旁注

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

      【讨论】:

        【解决方案5】:

        为什么不像这样注释掉rb 选项:

        [section]
        person=name
        id=000
        ; rb=
        

        然后使用这个很棒的oneliner:

        rb = parser.getint('section', 'rb') if parser.has_option('section', 'rb') else None
        

        【讨论】:

          猜你喜欢
          • 2017-09-23
          • 2011-05-01
          • 1970-01-01
          • 2020-07-18
          • 2021-01-13
          • 2017-05-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多