ConfigParser的内联注释

wim*_*wim 5 python ini comments configparser

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

但是我遇到的问题是内联注释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']
Run Code Online (Sandbox Code Playgroud)

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

小智 10

根据ConfigParser文档

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

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

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


ron*_*awn 7

[编辑]

现代 ConfigParser 支持内联注释。

settings_cfg = configparser.ConfigParser(inline_comment_prefixes="#")
Run Code Online (Sandbox Code Playgroud)

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


[原来的]

As SpliFF stated, the documentation says in-line comments are a no-no. Everything right of the first colon or equal sign is passed as the value, including comment delimiters.

Which sucks.

So, let's fix that:

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

The above function goes through every item in every section of a configParser object, splits the string on any '#' symbol, then strip()'s any white space from the leading or trailing edges of the remaining value, and writes back just the value, free of inline comments.

Here's a more pythonic, (if arguably less legible) list comprehension version of this function, that allows you to specifiy what character to split on:

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