python parsimonious: Parsing config file with multiple comment marks

475 views Asked by At

I'm trying to parse a config file where a the value of an entry may have a comment mark in it. So the rule is only the last comment mark is the divider between the value and the comment.

For example:

key1 = value
key2 = value;This is a comment
key3 = value;This is still value;This is a comment

Can I do that with parsimonious? How can I write a grammar that differentiates the last section after the ; sign?

Thank you.

2

There are 2 answers

3
Nurjan On

You can do something like this:

with open('config_file') as f:
    content = f.readlines()

for c in content:
   tmp = c.split(';') # Split line by `;`.
   comment = tmp[len(tmp) - 1]  # This is the comment part. 
   ...
0
Omer On

The best solution I could get from parsimonious was to treat the value and differentiate them when visiting the tree:

configGrammar = Grammar(r"""
file = "\n"* line* "\n"*
line = key ws? "=" ws? valueComment (";" valueComment)* "\n"
key = ~"[0-9A-z_]+"
valueComment = ~"[^;\n]*" 
ws = " "*
""")`