Skip to main content
 首页 » 编程设计

python之Centos Python 3 : ConfigParser using environment variables and cross references

2025年02月15日9lhb25

当我尝试使用 ConfigParser 获取值时,

  • 我无法从我的 .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} 

我得到以下输出,

$] python config_parse.py

server1

%(USER)

/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 takes precedence 的 HOSTNAME .

举个例子更容易理解:

>>> myConf.get('server_details', 'foo', vars={'FOO': 'BAR'}) 
'BAR' 

如果 vars 包含 FOO 的条目,则 get 对 foo 的调用(不区分大小写)将返回它的值,配置文件中的值实际上被忽略了。

这意味着对于 hostName,您实际上获得了 HOSTNAME 环境变量的值。 userName 不存在于 os.environ 中,因此您从配置文件中获取值:%(USER)。

因此,如果您使用 ExtendedInterpolations,请使用 ${...} 样式,如果您使用 BasicInterpolation,请使用 %(...)s 样式。你不能把两者混在一起。如果您盲目地传递 vars=os.environ,请注意环境变量将覆盖所有同名部分中的所有选项。根据应用程序运行的上下文,这可能与安全性相关。