来自外部部分的 Python ConfigParser 插值

标签 python python-2.7 python-2.x configparser python-2.4

使用 Python ConfigParser,是否可以跨外部部分使用插值?我的想法似乎告诉我,我在某处看到它是可能的,但我在搜索时找不到它。

此示例不起作用,但它可以让您了解我正在尝试做什么。

[section1]
root = /usr

[section2]
root = /usr/local

[section3]
dir1 = $(section1:root)/bin
dir2 = $(section2:root)/bin

请注意,我使用的是 Python 2.4。

最佳答案

在 python 3.2 及更高版本中,这是完全有效的:

[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}

编辑:

我刚看到你用的是python 2.4,所以不行python 2.4。它是在 python 3.2 中引入的 - See section 13.2.5 - ConfigParser Interpolation of values .

class configparser.ExtendedInterpolation

An alternative handler for interpolation which implements a more advanced syntax, used for instance in zc.buildout. Extended interpolation is using ${section:option} to denote a value from a foreign section. Interpolation can span multiple levels. For convenience, if the section: part is omitted, interpolation defaults to the current section (and possibly the default values from the special section). For example, the configuration specified above with basic interpolation, would look like this with extended interpolation:

   [Paths]
   home_dir: /Users
   my_dir: ${home_dir}/lumberjack
   my_pictures: ${my_dir}/Pictures

Values from other sections can be fetched as well:

   [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}

关于来自外部部分的 Python ConfigParser 插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7605124/

相关文章:

python - 运行 Python 程序直到特定时间

python - 无法在 Windows XP 上运行 Python EXE

python - 在本地主机上运行 python 脚本

python - 菜单要加多少?

python - 在 TestApp 和 Pyramid 中测试 AJAX 帖子

python - 嵌入式 Neo4j Python 创建或检查唯一关系

python - 在 python : Unknown characters 中读取 arduino 串行连接

python - 多处理:通过多个进程运行数组?

python - 为什么这个 argparse 代码在 Python 2 和 3 之间表现不同?

带有 ØÆÅ 字母的 Python 正则表达式