如何使用 python configparser 读取缩进部分

Käs*_*ker 3 python configparser

我尝试使用 python configparser 读取以下配置文件:

# test.conf
[section]
a = 0.3

        [subsection]
        b = 123
Run Code Online (Sandbox Code Playgroud)
# test.conf
[section]
a = 0.3

        [subsection]
        b = 123
Run Code Online (Sandbox Code Playgroud)

输出:

0.3

[subsection]
b = 123
Run Code Online (Sandbox Code Playgroud)

如果我删除缩进,则 a 会被正确读取。

如何使用 python configparser 正确读取带有缩进的配置文件?

根据文档,它应该可以工作:
https ://docs.python.org/3.8/library/configparser.html#supported-ini-file-struct

我使用Python 3.7.6

Vig*_*esh 5

在 python 错误跟踪器中提出错误后,我找到了一种阅读指定小节的方法。添加empty_lines_in_values=False到您的代码中。

错误跟踪器链接:https://bugs.python.org/issue41379

import configparser
conf = configparser.ConfigParser(empty_lines_in_values=False)
conf.read("./test.conf")
a = conf['section']['a']
print(a)
Run Code Online (Sandbox Code Playgroud)

输出:

hello
Run Code Online (Sandbox Code Playgroud)