Reference variable from another ini section

2019-06-20 10:09发布

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

2条回答
劫难
2楼-- · 2019-06-20 10:22

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

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

查看更多
叛逆
3楼-- · 2019-06-20 10:27

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'])
查看更多
登录 后发表回答