如何使用ConfigPars中已定义的变量

2024-05-21 07:20:27 发布

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

我在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


Tags: nameconfighomebasebinmydirexe
3条回答

可以使用ConfigParser插值

On top of the core functionality, SafeConfigParser supports interpolation. This means values can contain format strings which refer to other values in the same section, or values in a special DEFAULT section. Additional defaults can be provided on initialization.

For example:

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

would resolve the %(dir)s to the value of dir (frob in this case). All reference expansions are done on demand.

你的例子变成:

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

exe_dir: %(base_dir)s/bin

写“%(foo)s”,而不是“${foo}”。(参见http://docs.python.org/library/configparser.html并搜索“插值”。这适用于普通的ConfigParser或SafeConfigParser。)

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

相关问题 更多 >