ConfigPars的内联注释

2024-05-13 02:16:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个.in I文件里有这样的东西

[General]
verbosity = 3   ; inline comment

[Valid Area Codes]
; Input records will be checked to make sure they begin with one of the area 
; codes listed below.  

02    ; Central East New South Wales & Australian Capital Territory
03    ; South East Victoria & Tasmania
;04    ; Mobile Telephones Australia-wide
07    ; North East Queensland
08    ; Central & West Western Australia, South Australia & Northern Territory

但是,我有一个问题,内联注释在key = value行中工作,而不是在没有值行的key中工作。下面是创建ConfigParser对象的方法:

>>> import ConfigParser
>>> c = ConfigParser.SafeConfigParser(allow_no_value=True)
>>> c.read('example.ini')
['example.ini']
>>> c.get('General', 'verbosity')
'3'
>>> c.options('General')
['verbosity']
>>> c.options('Valid Area Codes')
['02    ; central east new south wales & australian capital territory', '03    ; south east victoria & tasmania', '07    ; north east queensland', '08    ; central & west western australia, south australia & northern territory']

如何设置配置分析器,以便内联注释对这两种情况都有效?


Tags: keyvalueareaconfigparsercodesgeneralcentralsouth
3条回答

[编辑]

现代ConfigParser支持内联注释。

settings_cfg = configparser.ConfigParser(inline_comment_prefixes="#")

但是,如果您想为支持的方法浪费函数声明,这里是我的原始文章:


[原件]

正如SpliFF所说,文档中说,行内注释是一个no-no。第一个冒号或等号右边的所有内容都作为值传递,包括注释分隔符。

真糟糕。

所以,让我们修正一下:

def removeInlineComments(cfgparser):
    for section in cfgparser.sections():
        for item in cfgparser.items(section):
            cfgparser.set(section, item[0], item[1].split("#")[0].strip())

上面的函数遍历configParser对象的每个部分中的每个项,拆分任何“#”符号上的字符串,然后从剩余值的前边或后边去掉()的任何空白,然后只写回该值,不包含内联注释。

下面是这个函数的pythonic(如果可以说不那么清晰)列表理解版本,它允许您指定要拆分的字符:

def removeInlineComments(cfgparser, delimiter):
    for section in cfgparser.sections():
        [cfgparser.set(section, item[0], item[1].split(delimiter)[0].strip()) for item in cfgparser.items(section)]

或许可以试试02= ; comment

根据ConfigParser文档

“配置文件可能包含注释,前缀为特定字符(#和;)。注释可以单独出现在空行中,也可以在包含值或节名称的行中输入

在您的示例中,您是在只包含键而不包含值的行中添加注释(因此它将不起作用),这就是您获得该输出的原因。

参考: http://docs.python.org/library/configparser.html#safeconfigparser-objects

相关问题 更多 >