Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Config parser read comment along with value

I have config file,

[local]
    variable1 : val1 ;#comment1
    variable2 : val2 ;#comment2

code like this reads only value of the key:

class Config(object):
    def __init__(self):
        self.config = ConfigParser.ConfigParser()
        self.config.read('config.py')

    def get_path(self):
        return self.config.get('local', 'variable1')

if __name__ == '__main__':
    c = Config()
    print c.get_path()

but i also want to read the comment present along with the value, any suggestions in this regards will be very helpful.

like image 958
avasal Avatar asked Feb 02 '12 10:02

avasal


1 Answers

Alas, this is not easily done in general case. Comments are supposed to be ignored by the parser.

In your specific case, it is easy, because # only serves as a comment character if it begins a line. So variable1's value will be "val1 #comment1". I suppose you use something like this, only less brittle:

val1_line = c.get('local', 'var1')
val1, comment = val1_line.split(' #') 

If the value of a 'comment' is needed, probably it is not a proper comment? Consider adding explicit keys for the 'comments', like this:

[local]
  var1: 108.5j
  var1_comment: remember, the flux capacitor capacitance is imaginary! 
like image 154
9000 Avatar answered Oct 04 '22 14:10

9000