来自外部部分的Python ConfigParser插值 [英] Python ConfigParser interpolation from foreign section

查看:151
本文介绍了来自外部部分的Python ConfigParser插值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Python ConfigParser,是否可以在外来部分之间使用插值?我的想法似乎告诉我,我已经看到某个地方有可能,但是搜索时找不到.

With Python ConfigParser, is it possible to use interpolation across foreign sections? My mind seems to tell me I've seen that it's possible somewhere, but I can't find it when searching.

此示例不起作用,但是可以让我对我要尝试做的事情有个了解.

This example doesn't work, but it's to give an idea of what I'm trying to do.

[section1]
root = /usr

[section2]
root = /usr/local

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

请注意,我正在使用Python 2.4.

Note that I'm using Python 2.4.

推荐答案

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

In python 3.2 and up this is perfectly valid:

[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 中引入的-请参阅第13.2.5节-值的ConfigParser插值.


I just saw that you are using python 2.4, so no, section interpolation cannot be done in python 2.4. It was introduced in python 3.2 - See section 13.2.5 - ConfigParser Interpolation of values.

configparser.ExtendedInterpolation

class configparser.ExtendedInterpolation

替代处理程序 用于实现更高级语法的插值,用于 zc.buildout中的实例.扩展插值正在使用 $ {section:option}表示来自外部部分的值. 插值可以跨越多个级别.为方便起见,如果 section:省略了一部分,插值默认为当前 部分(可能还有特殊部分的默认值). 例如,上面用basic指定的配置 插值,扩展插值看起来像这样:

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插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆