Saturday, September 29, 2012

Python3 configparse

configparse is a Python Module, part of the standard library, that read and writes config files and treats them almost like python dictionaries.

Well, almost.

Example dictionary
>>> test = {}
>>> test['Cleese'] = {'a':'1', 'b':'2'}
>>> test['John'] = {'f':True, 'g':'Hello'}

Example config object
>>> import configparser
>>> test = configparser.ConfigParser()
>>> test['Cleese'] = {'a':'1', 'b':'2'}
>>> test['John'] = {'f':True, 'g':'Hello'}


First, let's get the top-level list of sections:

Get the list of sections for a dict
>>>test
{'John': {'g': 'Hello', 'f': True}, 'Cleese': {'a': '1', 'b': '2'}}
>>> test.keys()
dict_keys(['John', 'Cleese'])
>>> list(test.keys())
['John', 'Cleese']

Let's try the same for a config object:
>>> test              
<configparser .configparser=".configparser" 0xb755c34c="0xb755c34c" at="at" object="object">
>>> test.keys()
KeysView(<configparser .configparser=".configparser" 0xb755c34c="0xb755c34c" at="at" object="object">)
>>> test.sections()
['Cleese', 'John']


Second, let's get the list of keys in one section:

Get the list of keys for one section of a dict
>>> test['Cleese']
{'a': '1', 'b': '2'}
>>> list(test['Cleese'].keys())
['a', 'b']

Same task for a config object:
>>> test['Cleese']
<section: cleese="cleese">
>>> test['Cleese'].sections()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'SectionProxy' object has no attribute 'sections'
>>> [a for a in test['Cleese']]
['a', 'b']


Third, let's get the key-value pairs in the same section:

Get the key-value pair for one section of a dict
>>> test['Cleese']
{'a': '1', 'b': '2'}
>>> [(a, test['Cleese'][a]) for a in test['Cleese'].keys()]
[('a', '1'), ('b', '2')]
>>> [print(a, test['Cleese'][a]) for a in test['Cleese'].keys()]
a 1
b 2
[None, None]

Same task for a config object:
>>> [(a, test['Cleese'][a]) for a in test['Cleese']]
[('a', '1'), ('b', '2')]
>>> [print(a, test['Cleese'][a]) for a in test['Cleese']]
a 1
b 2
[None, None]


Finally, let's dump ALL the key-value pairs in the whole object:

Iterate and dump all key-value pairs in a dict
>>> [[print(b, test[a][b]) for b in test[a].keys()] for a in test.keys()]
g Hello
f True
a 1
b 2
[[None, None], [None, None]]

Dump all in a configparse object
>>> [[print(b, test[a][b]) for b in test[a]] for a in test]
a 1
b 2
g Hello
f True
[[], [None, None], [None, None]]
>>> [[print(b, test[a][b]) for b in test[a].keys()] for a in test.sections()]
a 1
b 2
g Hello
f True
[[None, None], [None, None]]


No comments:

Post a Comment