问题
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