使用 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不能进行段插值em>。它是在 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/