gpt4 book ai didi

python - python 2.7 中的 ConfigParser VS SafeConfigParser

转载 作者:太空狗 更新时间:2023-10-29 17:32:47 27 4
gpt4 key购买 nike

ConfigParserSafeConfigParser 有什么区别?确切地说,为什么后者更安全? ConfigParser 的“不安全”是什么?我知道 SafeConfigParser 继承了 ConfigParser,它有什么不同?

最佳答案

SafeConfigParser实现不同的 set(section, option, value) 方法,该方法将引发 NoSectionError如果该部分不存在,如果 value 不是字符串,则返回 TypeError

这允许更多地控制解析器的行为,example来自文档:

try:
config.set(section2, option, config.get(section1, option, 1))
except ConfigParser.NoSectionError:
# Create non-existent section
config.add_section(section2)
opt_move(config, section1, section2, option)
else:
config.remove_option(section1, option)

From documentation: It also support interpolation. This means values can contain format strings which refer to other values in the same section, or values in a special DEFAULT section. Additional defaults can be provided on initialization.

更新

我刚刚检查了 source code SafeConfigParser,即使 ConfigParser 确实也允许插值,SafeConfigParser 也提供了它的更新版本 documentation描述为魔法插值功能的更理智和更可预测的变体

例如,如果引用错误或“%”字符后出现语法错误,它将引发 InterpolationSyntaxError

更新 2

这可能有助于精确确定 SafeConfigParserhas been renamed to ConfigParser in Python 3.2 .如果您想知道在 python 2.7 中应该使用 SafeConfigParser 还是 ConfigParser 中的哪一个,请使用第一个(除非您有非常具体的理由使用第二个)

您还可以通过以下方式更轻松地过渡到 python 3+ ( which should happen soon ):

from ConfigParser import SafeConfigParser as ConfigParser

关于python - python 2.7 中的 ConfigParser VS SafeConfigParser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37937418/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com