来自外部节的Python ConfigParser插值

2024-04-27 16:24:57 发布

您现在位置:Python中文网/ 问答频道 /正文

使用Python ConfigParser,是否可以跨外部部分使用插值?我的大脑似乎告诉我,我已经看到它可能在某个地方,但我找不到它时。

这个例子不起作用,但它能让你知道我在做什么。

[section1]
root = /usr

[section2]
root = /usr/local

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

注意,我使用的是Python2.4。


Tags: binusrlocal地方rootconfigparser例子插值
3条回答

如果您一直在使用python 2.7,并且需要进行横截面插值,那么使用regexps手工进行插值就足够简单了。

代码如下:

INTERPOLATION_RE = re.compile(r"\$\{(?:(?P<section>[^:]+):)?(?P<key>[^}]+)\}")

def load_something_from_cp(cp, section="section"):
    result = []
    def interpolate_func(match):
        d = match.groupdict()
        section = d.get('section', section)
        key = d.get('key')
        return cp.get(section, key)
    for k, v in cp.items(section):
        v = re.sub(INTERPOLATION_RE, interpolate_func, v)
        result.append(
            (v, k)
        )
    return result

警告:

  • 插值中没有递归
  • 在分析许多节时,您需要以某种方式猜测当前节。

在Python3.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,也可以通过其他部分的插值来访问此处定义的值。

相关问题 更多 >