【问题标题】:How to make a ConfigParser return a default value instead of raising a NoOptionError?如何使 ConfigParser 返回默认值而不是引发 NoOptionError?
【发布时间】:2016-03-04 21:51:14
【问题描述】:

我有一个定义了一些选项的配置文件。有时,如果没有找到请求的选项,我想忽略错误并返回None

setting.cfg:

[Set]
ip=some_ip
verify=yes     #if verify does not exist here --> verify=None

test.py:

import sys
import ConfigParser

file="setting.cfg"

class ReadFile:
   def read_cfg_file(self):
      configParser = ConfigParser.RawConfigParser(allow_no_value=True)
      if os.path.isfile(file):
          configParser.read(file)
      else:
          sys.exit(1)
      try:
          verify = configParser.get('Set', 'verify')
      except ConfigParser.NoOptionError:
          pass

      return verify,and,lots,of,other,values

如果我这样处理它,我将无法返回值,因为如果找不到 'verify' 选项,它只会通过。

如果找不到选项,有什么方法可以忽略错误,而是返回None

例如,像这样:

verify = configParser.get('Set', 'verify')
if not verify:
    verify=False

【问题讨论】:

    标签: python python-2.7 exception-handling configparser


    【解决方案1】:

    如果是我,我会从 RawConfigParser 派生一个新的配置解析器类,只添加新的特殊行为,如下所示:

    from ConfigParser import RawConfigParser, NoOptionError
    from StringIO import StringIO
    from collections import defaultdict
    
    class MyConfigParser(RawConfigParser):
        def get(self, section, option):
            try:
                return RawConfigParser.get(self, section, option)
            except NoOptionError:
                return None
    
    
    settings=StringIO('''
    [Set]
    ip=192.0.2.76
    verify=yes
    [Set2]
    ip=192.0.2.74
    ''')
    
    cfg=MyConfigParser(allow_no_value=True)
    cfg.readfp(settings)
    
    assert cfg.get('Set', 'verify') ==  'yes'
    assert cfg.get('Set2', 'verify') == None
    

    【讨论】:

      【解决方案2】:

      Python 3 的 configparser 模块是 much-improved 并提供了一个 get(option, default) 方法。

      Python 2 的 ConfigParsers 允许使用 DEFAULT 部分 (supplied at construction time),但在这种情况下,您必须提前知道每个选项的默认值。

      如果您使用的是 Python 2 并且需要在调用站点提供默认值,那么按照 Rob 的回答进行子分类似乎是可行的方法。

      【讨论】:

        【解决方案3】:

        Python 2.7.12

        您可以利用 ConfigParser()get() 方法,允许您在调用时指定默认字典:

        $ cat myconf.txt
        [files]
        path1 = /tmp
        path2 = /usr/bin
        path3 =
        
        $ ipython
        ...
        In [1]: import ConfigParser
           ...: 
           ...: cp = ConfigParser.ConfigParser(allow_no_value=True)
           ...: cp.read('myconf.txt')
           ...: defaults = { 'path4' : '/opt/include'}
           ...: print 'path1:', cp.get('files', 'path1', 0, defaults)
           ...: print 'path3:', cp.get('files', 'path3', 0, defaults)
           ...: print 'path4:', cp.get('files', 'path4', 0, defaults)
           ...: 
        path1: /tmp
        path3: 
        path4: /opt/include
        

        【讨论】:

          猜你喜欢
          • 2019-06-22
          • 2020-06-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多