【问题标题】:How to use variables already defined in ConfigParser如何使用已在 ConfigParser 中定义的变量
【发布时间】:2011-02-15 01:45:19
【问题描述】:

我在 Python 中使用 ConfigParser

config.ini 是

[general]
name: my_name
base_dir: /home/myhome/exp

exe_dir: ${base_dir}/bin

这里我想要exp_dir 变成/home/myhome/exp/bin 而不是${base_dir}/bin

这意味着${base_dir} 将被替换为/home/myhome/exp automatically

【问题讨论】:

    标签: python configparser


    【解决方案1】:

    可以使用ConfigParser插值

    除了核心功能之外, SafeConfigParser 支持 插值。这意味着值可以 包含引用的格式字符串 同一部分中的其他值,或 特殊的 DEFAULT 部分中的值。 可以提供额外的默认值 初始化。

    例如:

    [My Section] 
    foodir: %(dir)s/whatever 
    dir=frob 
    long: this value continues    
        in the next line 
    

    会将 %(dir)s 解析为值 dir (在这种情况下是 frob)。全部 参考扩展完成 需求。

    你的例子变成了:

    [general]
    name: my_name
    base_dir: /home/myhome/exp
    
    exe_dir: %(base_dir)s/bin
    

    【讨论】:

      【解决方案2】:

      用“%(foo)s”代替“${foo}”。 (请参阅http://docs.python.org/library/configparser.html 并搜索“插值”。这适用于普通的 ConfigParser 或 SafeConfigParser。)

      【讨论】:

      • 谢谢!在我的代码中,%(foo) 后面缺少的s 让我发疯。有时您必须先查看源代码,然后才能意识到它也在文档中! ;-)
      【解决方案3】:

      在 Python 3 中,您可以使用 ${base_dir}/bin,而 extended interpolation 允许您使用其他部分的变量。示例:

      [Common]
      home_dir: /Users
      library_dir: /Library
      system_dir: /System
      macports_dir: /opt/local
      
      [Frameworks]
      Python: 3.2
      path: ${Common:system_dir}/Library/Frameworks/
      
      [Arthur]
      nickname: Two Sheds
      last_name: Jackson
      my_dir: ${Common:home_dir}/twosheds
      my_pictures: ${my_dir}/Pictures
      python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
      

      【讨论】:

      • configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())
      猜你喜欢
      • 2017-11-08
      • 2020-02-05
      • 2015-01-21
      • 2018-10-16
      • 2023-04-04
      • 2018-03-20
      • 1970-01-01
      • 1970-01-01
      • 2023-01-11
      相关资源
      最近更新 更多