(使用 Python 3.4.3)
我想在我的配置文件中使用环境变量,并且我读到应该使用 SafeConfigParser
和 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
解析为 /home/myuser/.config/my_folder
但不想要 SafeConfigParser
将我的所有环境变量添加到其每个部分。
最佳答案
如果我正确理解了您的问题以及您想要做什么,您可以通过不提供os.environ
来避免问题SafeConfigParser
的参数。当您实际使用 get()
方法检索值时,请将其用作 vars
关键字参数的值。
这之所以有效,是因为它避免了从所有环境变量创建默认部分,但允许在引用它们的值用于插值/扩展目的时使用它们的值。
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))
关于python - 安全配置解析器 : sections and environment variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39408101/