(使用Python 3.4.3)
我想在我的配置文件中使用环境变量,我读到我应该使用SafeConfigParser
with os.environ
作为参数来实现它。
[test]
mytest = %(HOME)s/.config/my_folder
由于我需要获取一个部分中的所有选项,因此我正在执行以下代码:
userConfig = SafeConfigParser(os.environ)
userConfig.read(mainConfigFile)
for section in userConfig.sections():
for item in userConfig.options(section):
print( "### " + section + " -> " + item)
我的结果不是我所期望的。正如您在下面看到的,它不仅有我在我的部分中拥有的选项([test]\mytest
),还有所有环境变量:
### test -> mytest
### test -> path
### test -> lc_time
### test -> xdg_runtime_dir
### test -> vte_version
### test -> gnome_keyring_control
### test -> user
我究竟做错了什么?
我希望能够解析[test]\mytest
as /home/myuser/.config/my_folder
但不想要SafeConfigParser
将我的所有环境变量添加到其每个部分。
如果我理解了你的问题以及你想要正确做什么,你可以通过以下方式避免这个问题not供应os.environ
作为参数SafeConfigParser
。相反,使用它作为vars
当您实际使用以下命令检索值时关键字参数的值get()
method.
这是有效的,因为它避免了创建default所有环境变量中的部分,但允许在出于插值/扩展目的引用时使用它们的值。
userConfig = SafeConfigParser() # DON'T use os.environ here
userConfig.read(mainConfigFile)
for section in userConfig.sections():
for item in userConfig.options(section):
value = userConfig.get(section, item, vars=os.environ) # use it here
print('### [{}] -> {}: {!r}'.format(section, item, value))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)