python 2.7中的ConfigParser VS SafeConfigParser

Tic*_*cks 13 python configparser python-2.7

ConfigParser和之间有什么区别SafeConfigParser?那么,为什么后者更安全呢?什么是'不安全' ConfigParser?我知道SafeConfigParser继承了ConfigParser它,它做了什么不同?

oli*_*x14 9

SafeConfigParser实现了不同的set(section, option, value)方法,这将提高一个NoSectionError如果节不存在,并且TypeError如果value不是字符串.

这允许更多地控制解析器的行为,这是文档中的一个示例:

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)
Run Code Online (Sandbox Code Playgroud)

来自文档:它还支持插值.这意味着值可以包含引用同一节中其他值的格式字符串,或特殊DEFAULT节中的值.初始化时可以提供其他默认值.

更新

我刚刚检查了源代码SafeConfigParser,即使这是真的,ConfigParser也允许插值,SafeConfigParser提供了它的一个更新版本的文档描述为神奇的插值功能的更理智,更可预见的变体.

例如,InterpolationSyntaxError如果出现错误引用或者在'%'字符后出现语法错误,它将引发一个.

更新2

这可能有助于精确地将SafeConfigParser重命名为Python 3.2中的ConfigParser.如果你想知道在python 2.7中应该使用哪个SafeConfigParser或哪个ConfigParser,请使用第一个(除非你有一个非常具体的理由使用第二个)

您还可以通过以下方式更轻松地将来过渡到python 3+(这应该很快就会发生):

from ConfigParser import SafeConfigParser as ConfigParser
Run Code Online (Sandbox Code Playgroud)