当我尝试使用配置解析器获取值时,
-
我无法从.ini文件中的环境变量中获取某些值
-
内插变量名称是打印变量,因为它没有值替换。
下面是我的代码,
config_parse.py:
import os
import configparser
myConf = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())
myConf.read('config_data.ini')
print( myConf.get('server_details', 'hostName', vars=os.environ))
print( myConf.get('server_details', 'userName', vars=os.environ))
print( myConf.get('log_path', 'mntPath', vars=os.environ))
exit(0)
config_data.ini:
[server_details]
hostName: %(HOSTNAME)
; Below value are not getting substituted from environment variable
userName: %(USER)
password: passw0rd
[log_path]
instance: %(SERVER_INSTANCE)
mntPath: /net/server1/mnt/data0
; server_details:hostname and instance values are not getting substituted
testbedMntPath: ${mntPath}/${server_details:userName}/my_logs/${server_details:hostName}${instance}
我得到以下输出,
$] 蟒蛇config_parse.py
服务器1
%(用户(
/net/server1/mnt/data0/%(USER(/my_logs/%(HOSTNAME(%(SERVER_INSTANCE(
$]
您正在使用ExtendedInterpolation
,它使用${section:option}
语法。
您获得myConf.get('server_details', 'hostName', vars=os.environ)
server1
的原因不是因为hostName = %(HOSTNAME)
是插值的,而是因为vars
中的HOSTNAME
优先。
通过一个例子更容易看到:
>>> myConf.get('server_details', 'foo', vars={'FOO': 'BAR'})
'BAR'
如果vars
包含 FOO
的条目,则对 foo
的get
调用(不区分大小写(将返回其值,配置文件中的值实际上被忽略。
因此,这意味着对于hostName
,您可以直接获得HOSTNAME
环境变量的值。 userName
中不存在 os.environ
,因此您可以从配置文件中获取值:%(USER)
。
因此,如果使用扩展插值,请使用${...}
样式,如果使用基本插值,请使用%(...)s
样式。您不能同时使用两者。如果你盲目地传递vars=os.environ
,请注意,环境变量将覆盖所有部分中具有相同名称的所有选项。根据应用程序运行的上下文,这可能与安全性相关。