Inline comments for ConfigParser

10,206

Solution 1

According to the ConfigParser documentation

"Configuration files may include comments, prefixed by specific characters (# and ;). Comments may appear on their own in an otherwise empty line, or may be entered in lines holding values or section names"

In your case you are adding comments in lines holding just keys without values (hence it will not work) , and that's why you are getting that output.

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

Solution 2

[EDIT]

Modern ConfigParser supports in-line comments.

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

However, if you want to waste a function declaration for supported methods, here's my original post:


[ORIGINAL]

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

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)]
Share:
10,206
wim
Author by

wim

Hi from Chicago! Python dev with interest in mathematics, music, robotics and computer vision. I hope my Q&A have been helpful for you. If one of my answers has saved your butt today and you would like a way to say thank you, then feel free to buy me a coffee! :-D [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo *Click*

Updated on June 04, 2022

Comments

  • wim
    wim almost 2 years

    I have stuff like this in an .ini file

    [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
    

    However I have the problem that inline comments are working in the key = value line, but not in the key with no value lines. Here is how I am creating my ConfigParser object:

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

    How can I setup the config parser so that inline comments work for both cases?

  • wim
    wim about 12 years
    It doesn't really work properly, it puts the "; comment" in as the value.
  • wim
    wim about 12 years
    I did notice this in the docs, but I thought there must be a way to customize it. It seems ugly and broken that inline comments work in some cases, and not in others.. they should either work everywhere or be disallowed completely!
  • V123456
    V123456 about 12 years
    I agree, I looked up the ConfigParser code as well. There is no way that it can be customized. First I thought that it was a bug in the config parser code itself, but then I went back and read the doc carefully and saw that they have specified it explicitly.
  • Bill Gale
    Bill Gale almost 8 years
    The current Python 3.5.2 ConfigParser documentation mentions a customization capability for this. [You can use comments] # like this ; or this # By default only in an empty line. # Inline comments can be harmful because they prevent users # from using the delimiting characters as parts of values. # That being said, this can be customized.
  • masky007
    masky007 over 2 years
    settings_cfg = configparser.ConfigParser(inline_comment_prefixes="#") is just not working for me... I am using configparser-5.2.0 with Python 3 edit: it still prints the #comment when i try to print the value