python - 安全配置解析器 : sections and environment variables

标签 python environment-variables python-3.4 configparser

(使用 Python 3.4.3)

我想在我的配置文件中使用环境变量,并且我读到应该使用 SafeConfigParseros.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/

相关文章:

python - python 正确从文本文件中读取多个列表

reactjs - 如何配置我的 package.json 文件以从操作系统中设置的环境变量读取?

linux - ubuntu10.4设置环境变量

用于匹配文件名的 Python 正则表达式。使用 os.walk() 获取文件名

python - 使用 Python 访问网站

python - 绘图库;散点图标记,圆圈内的点

tkinter - 如何更改 tkinter 应用程序的整体主题?

python - 元组索引超出范围? python 3.4.2

python - `For x in locals():` -- 运行时错误 : Why does locals() change size?

c++ - 从 C++ 运行代码后解锁绑定(bind)(在 R 中)的问题