Python配置解析器如何从一个节中获取所有值?

64 投票
2 回答
82641 浏览
提问于 2025-04-17 08:43

我想用配置解析器获取某个部分的所有值。

我用了这个方法,但它只返回了第一个值。

def ConfigSectionMap(section):
  dict1 = {}
  options = Config.options(section)
  for option in options:
    try:
      dict1[option] = Config.get(section, option)
      if dict1[option] == -1:
        DebugPrint("skip: %s" % option)
    except:
      print("exception on %s!" % option)
      dict1[option] = None
    return dict1


  Config = ConfigParser.ConfigParser()
  Config.read("/etc/harvest.conf")
  print ConfigSectionMap("files").values()

2 个回答

15

如果顺序很重要的话,你可以把它做成一个列表。

list(Config.items('Section'))
149

把它变成一个字典:

dict(Config.items('Section'))

撰写回答