【问题标题】:Reading a configuration file in Python (storing/reading nested data with ConfigParser)在 Python 中读取配置文件(使用 ConfigParser 存储/读取嵌套数据)
【发布时间】:2012-03-06 17:29:24
【问题描述】:

我正在编写一个列表处理脚本,该脚本需要读取列表中每个项目的配置数据。配置数据最好用嵌套树表示。

我通常会使用 YAML 来存储数据 - 但我认为使用 ConfigParser 将是一种更 Python 的方法 - 并使脚本对其他 Python 编码器更加“透明” - 因为数量惊人的人不熟悉YAML 格式。

我快速浏览了configParser documentation,但我无法确定它是否可以处理嵌套数据。

我的配置数据将具有以下结构:

<markers>
    <marker>
        <date></date>
        <value></value>
    </marker>
</markers>
<items>
    <item>
        <start></start>
        <end></end>
        <mcc>
           <chg>
                <date></date>
                <ival></ival>
                <fval></fval>
           </chg>
        </mcc>
    </item>
</items>

我可以使用 ConfigParser 在配置文件中读取/(写入?)这种嵌套数据吗? (我更感兴趣的是能够读取而不是编写配置文件。如果需要,我不介意手动编写配置文件)。

【问题讨论】:

  • 恕我直言,熟悉并不意味着“透明”,甚至是最好的东西。我不知道有一个真正的 Python 编码员在半小时内无法学习和理解 YAML——如果你不详细说明的话,它是最简单和人类可读的格式之一:)。使用 YAML - 带来大众之美!附言很抱歉给您带来不便。
  • 仅供参考,您当然可以使用 XML!

标签: python configuration pyyaml


【解决方案1】:

不,configparser 不支持嵌套。你可以看看configObj。它很成熟,应用也很广泛。

【讨论】:

【解决方案2】:

根据您的 xml 数据,您需要部分和小节。所以你可以使用ConfigParser,但你必须给子部分赋予一些意义,比如

[markers]
[markers.marker]
date=''
value=''

[items]
[items.item]
start=''
end=''
[items.item.mcc]
[items.item.mcc.chg]
date=''
ival=''
fval=''

那么你必须重写getsection函数来获取嵌套数据。

【讨论】:

    【解决方案3】:

    TOML 配置文件遵循与INI 文件类似的语法并允许嵌套结构。见官方规范here和对应的python库here

    例子:

    >>> import toml
    >>> toml_string = """
    ... # This is a TOML document.
    ...
    ... title = "TOML Example"
    ...
    ... [owner]
    ... name = "Tom Preston-Werner"
    ... dob = 1979-05-27T07:32:00-08:00 # First class dates
    ...
    ... [database]
    ... server = "192.168.1.1"
    ... ports = [ 8001, 8001, 8002 ]
    ... connection_max = 5000
    ... enabled = true
    ...
    ... [servers]
    ...
    ...   # Indentation (tabs and/or spaces) is allowed but not required
    ...   [servers.alpha]
    ...   ip = "10.0.0.1"
    ...   dc = "eqdc10"
    ...
    ...   [servers.beta]
    ...   ip = "10.0.0.2"
    ...   dc = "eqdc10"
    ...
    ... [clients]
    ... data = [ ["gamma", "delta"], [1, 2] ]
    ...
    ... # Line breaks are OK when inside arrays
    ... hosts = [
    ...   "alpha",
    ...   "omega"
    ... ]
    ... """
    >>> parsed_toml = toml.loads(toml_string)
    

    【讨论】:

      猜你喜欢
      • 2021-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-28
      • 1970-01-01
      相关资源
      最近更新 更多