简体   繁体   中英

Python configparser read a dictionary

I was wondering if there is a way to establish a dictionary in a config file and use python config parser to read it?

Thanks.

Use eval and simply execute the configuration file.

with open('the_config','r') as config_file:
    config= eval( config_file.read() )

You will see comments telling you this is evil and a security hole and lots of other things. However, it's exactly as secure as your Python source.

configparser does not support that, but maybe you could be interested in taking a look at the json module.

Adapting an example from the official doc :

>>> import json
>>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
>>> print(s)
{
    "4": 5, 
    "6": 7
}
>>> json.loads(s)
{'4': 5, '6': 7}

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