Inline comments for ConfigParser

wim picture wim · Feb 29, 2012 · Viewed 8.6k times · Source

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?

Answer

V123456 picture V123456 · Feb 29, 2012

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