Reference variable from another ini section

假装没事ソ 提交于 2020-01-02 02:48:15

问题


Is it possible to reference a variable within an ini from another section?

I know you can do the following

[env]
dir  = /home/a
dir2 = %(dir)s/b

But what happens if I have two sections and want to reference the variable from that section?

[env]
name =  DEV

[dir]
home = /home/<name from env here>/scripts

Thanks


回答1:


See the documentation on Python 3's configparser. Create a parser with extended interpolation. Use ${section:option} syntax to reference options from other sections.

from configparser import ConfigParser, ExtendedInterpolation

parser = ConfigParser(interpolation=ExtendedInterpolation())
parser.read_string('''[env]
name = DEV

[dir]
home = /home/${env:name}/scripts
''')

print(parser['dir']['home'])



回答2:


Python 2.x not support cross ref. from another section.

But you can use [DEFAULT]. The definitions in this section are shareable specially.



来源:https://stackoverflow.com/questions/25049276/reference-variable-from-another-ini-section

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