eme*_*eth 13 python configparser
我在Python中使用ConfigParser
config.ini是
[general]
name: my_name
base_dir: /home/myhome/exp
exe_dir: ${base_dir}/bin
Run Code Online (Sandbox Code Playgroud)
在这里我想exp_dir
变得/home/myhome/exp/bin
不${base_dir}/bin
.
它意味着${base_dir}
将被替代/home/myhome/exp automatically
.
Rod*_*Rod 21
您可以使用ConfigParser插值
除了核心功能之外,SafeConfigParser还支持插值.这意味着值可以包含引用同一节中其他值的格式字符串,或特殊DEFAULT节中的值.初始化时可以提供其他默认值.
例如:
Run Code Online (Sandbox Code Playgroud)[My Section] foodir: %(dir)s/whatever dir=frob long: this value continues in the next line
会将%(dir)s解析为dir的值(在这种情况下为frob).所有参考扩展都是按需完成的.
你的例子变成:
[general]
name: my_name
base_dir: /home/myhome/exp
exe_dir: %(base_dir)s/bin
Run Code Online (Sandbox Code Playgroud)
而不是"$ {foo}",写"%(foo)s".(请参阅http://docs.python.org/library/configparser.html并搜索"interpolation".这适用于普通的ConfigParser或SafeConfigParser.)
在Python 3中,您可以使用${base_dir}/bin
,并且扩展插值允许您使用其他部分的变量。例子:
[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}
Run Code Online (Sandbox Code Playgroud)