How to use variables already defined in ConfigParser

送分小仙女□ 提交于 2019-11-30 01:28:37

问题


I'm using ConfigParser in Python

config.ini is

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

exe_dir: ${base_dir}/bin

Here I want exp_dir becomes /home/myhome/exp/bin not ${base_dir}/bin.

It means ${base_dir} would be substituted to /home/myhome/exp automatically.


回答1:


You can use ConfigParser interpolation

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.

Your example becomes:

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

exe_dir: %(base_dir)s/bin



回答2:


Instead of "${foo}", write "%(foo)s". (See http://docs.python.org/library/configparser.html and search for "interpolation". This works for either an ordinary ConfigParser or a SafeConfigParser.)




回答3:


In Python 3, you can use ${base_dir}/bin, and the extended interpolation allows you to use variables from other sections. Example:

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


来源:https://stackoverflow.com/questions/4999190/how-to-use-variables-already-defined-in-configparser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!