ConfigParser的内联注释

问题描述 投票:4回答:3

我在.ini文件中有这样的东西

[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']

如何设置配置解析器,以便内联注释适用于这两种情况?

python comments ini configparser
3个回答
10
投票

根据ConfigParser文档

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

在你的情况下,你只是在没有值的行中添加注释(因此它不起作用),这就是你得到那个输出的原因。

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


2
投票

[编辑]

Modern ConfigParser支持内联注释。

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

但是,如果你想浪费一个支持方法的函数声明,这是我的原始帖子:


[原版的]

正如SpliFF所说,文档说在线评论是禁忌。第一个冒号或等号的所有右侧都作为值传递,包括注释分隔符。

哪个很烂。

所以,让我们解决这个问题:

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)]

0
投票

也许尝试02= ; comment而不是。

© www.soinside.com 2019 - 2024. All rights reserved.