简体   繁体   中英

Extending configobj on python to handle custom comment marker

I have a config file, key and value pairs without sections. I'm trying to use configobj to parse it, but comments on my config files start with // rather than #

In the configobj documentation I found an example but it doesn't work to me:

from configobj import ConfigObj

class ConfigObjCustom(ConfigObj):
    COMMENT_MARKERS = ['//']


config = ConfigObjCustom('hello.conf')

Is there a way to extend configobj to support other comment markers?

I also could not get the suggested example with inheriting a new object with changed COMMENT_MARKERS to work.

But the steamroller approach to solve the problem would be to read the file, replace the comments and then feed it to configobj. I did a quick test and it worked well enough:

from configobj import ConfigObj
import re
from io import StringIO

with open('hello.conf') as f:
    file_contents = re.sub('//', '#', f.read())

print(config['SOMEKEY'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM