来自另一个ini部分的参考变量 [英] Reference variable from another ini section

查看:62
本文介绍了来自另一个ini部分的参考变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从其他部分引用ini中的变量?

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

谢谢

推荐答案

请参阅 Python 3的文档。 configparser 。创建具有扩展插值的解析器。使用 $ {section:option} 语法来引用其他部分的选项。

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'])

这篇关于来自另一个ini部分的参考变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆