An object to read, create, and write config files.
Parse a config file or create a config file object.
Parse a config file or create a config file object.
Methods
__init__([infile, options, configspec, ...]) | Parse a config file or create a config file object. |
as_bool(key) | Accepts a key as input. |
as_float(key) | A convenience method which coerces the specified value to a float. |
as_int(key) | A convenience method which coerces the specified value to an integer. |
as_list(key) | A convenience method which fetches the specified value, guaranteeing that it is a list. |
clear() | A version of clear that also affects scalars/sections Also clears comments and configspec. |
copy(() -> a shallow copy of D) | |
dict() | Return a deepcopy of self as a dictionary. |
fromkeys(...) | v defaults to None. |
get(key[, default]) | A version of get that doesn’t bypass string interpolation. |
has_key((k) -> True if D has a key k, else False) | |
items(() -> list of D’s (key, value) pairs, ...) | |
iteritems(() -> an iterator over the (key, ...) | |
iterkeys(() -> an iterator over the keys of D) | |
itervalues(...) | |
keys(() -> list of D’s keys) | |
merge(indict) | A recursive update - useful for merging config files. |
pop(key[, default]) | ‘D.pop(k[,d]) -> v, remove specified key and return the corresponding value. |
popitem() | Pops the first (key,val) |
reload() | Reload a ConfigObj from file. |
rename(oldkey, newkey) | Change a keyname to another, without changing position in sequence. |
reset() | Clear ConfigObj instance and restore to ‘freshly created’ state. |
restore_default(key) | Restore (and return) default value for the specified key. |
restore_defaults() | Recursively restore default values to all members that have them. |
setdefault(key[, default]) | A version of setdefault that sets sequence if appropriate. |
update(indict) | A version of update that uses our __setitem__. |
validate(validator[, preserve_errors, copy, ...]) | Test the ConfigObj against a configspec. |
values(() -> list of D’s values) | |
viewitems(...) | |
viewkeys(...) | |
viewvalues(...) | |
walk(function[, raise_errors, call_on_sections]) | Walk every member and call a function on the keyword and value. |
write([outfile, section]) | Write the current ConfigObj as a file |
Accepts a key as input. The corresponding value must be a string or the objects (True or 1) or (False or 0). We allow 0 and 1 to retain compatibility with Python 2.2.
If the string is one of True, On, Yes, or 1 it returns True.
If the string is one of False, Off, No, or 0 it returns False.
as_bool is not case sensitive.
Any other input will raise a ValueError.
>>> a = ConfigObj()
>>> a['a'] = 'fish'
>>> a.as_bool('a')
Traceback (most recent call last):
ValueError: Value "fish" is neither True nor False
>>> a['b'] = 'True'
>>> a.as_bool('b')
1
>>> a['b'] = 'off'
>>> a.as_bool('b')
0
A convenience method which coerces the specified value to a float.
If the value is an invalid literal for float, a ValueError will be raised.
>>> a = ConfigObj()
>>> a['a'] = 'fish'
>>> a.as_float('a')
Traceback (most recent call last):
ValueError: invalid literal for float(): fish
>>> a['b'] = '1'
>>> a.as_float('b')
1.0
>>> a['b'] = '3.2'
>>> a.as_float('b')
3.2...
A convenience method which coerces the specified value to an integer.
If the value is an invalid literal for int, a ValueError will be raised.
>>> a = ConfigObj()
>>> a['a'] = 'fish'
>>> a.as_int('a')
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: 'fish'
>>> a['b'] = '1'
>>> a.as_int('b')
1
>>> a['b'] = '3.2'
>>> a.as_int('b')
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: '3.2'
A convenience method which fetches the specified value, guaranteeing that it is a list.
>>> a = ConfigObj()
>>> a['a'] = 1
>>> a.as_list('a')
[1]
>>> a['a'] = (1,)
>>> a.as_list('a')
[1]
>>> a['a'] = [1]
>>> a.as_list('a')
[1]
A version of clear that also affects scalars/sections Also clears comments and configspec.
Return a deepcopy of self as a dictionary.
All members that are Section instances are recursively turned to ordinary dictionaries - by calling their dict method.
>>> n = a.dict()
>>> n == a
1
>>> n is a
0
v defaults to None.
A version of get that doesn’t bypass string interpolation.
A recursive update - useful for merging config files.
>>> a = '''[section1]
... option1 = True
... [[subsection]]
... more_options = False
... # end of file'''.splitlines()
>>> b = '''# File is user.ini
... [section1]
... option1 = False
... # end of file'''.splitlines()
>>> c1 = ConfigObj(b)
>>> c2 = ConfigObj(a)
>>> c2.merge(c1)
>>> c2
ConfigObj({'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}})
‘D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised’
Pops the first (key,val)
Reload a ConfigObj from file.
This method raises a ReloadError if the ConfigObj doesn’t have a filename attribute pointing to a file.
Change a keyname to another, without changing position in sequence.
Implemented so that transformations can be made on keys, as well as on values. (used by encode and decode)
Also renames comments.
Clear ConfigObj instance and restore to ‘freshly created’ state.
Restore (and return) default value for the specified key.
This method will only work for a ConfigObj that was created with a configspec and has been validated.
If there is no default value for this key, KeyError is raised.
Recursively restore default values to all members that have them.
This method will only work for a ConfigObj that was created with a configspec and has been validated.
It doesn’t delete or modify entries without default values.
A version of setdefault that sets sequence if appropriate.
A version of update that uses our __setitem__.
Test the ConfigObj against a configspec.
It uses the validator object from validate.py.
To run validate on the current ConfigObj, call:
test = config.validate(validator)
(Normally having previously passed in the configspec when the ConfigObj was created - you can dynamically assign a dictionary of checks to the configspec attribute of a section though).
It returns True if everything passes, or a dictionary of pass/fails (True/False). If every member of a subsection passes, it will just have the value True. (It also returns False if all members fail).
In addition, it converts the values from strings to their native types if their checks pass (and stringify is set).
If preserve_errors is True (False is default) then instead of a marking a fail with a False, it will preserve the actual exception object. This can contain info about the reason for failure. For example the VdtValueTooSmallError indicates that the value supplied was too small. If a value (or section) is missing it will still be marked as False.
You must have the validate module to use preserve_errors=True.
You can then use the flatten_errors function to turn your nested results dictionary into a flattened list of failures - useful for displaying meaningful error messages.
Walk every member and call a function on the keyword and value.
Return a dictionary of the return values
If the function raises an exception, raise the errror unless raise_errors=False, in which case set the return value to False.
Any unrecognised keyword arguments you pass to walk, will be pased on to the function you pass in.
Note: if call_on_sections is True then - on encountering a subsection, first the function is called for the whole subsection, and then recurses into it’s members. This means your function must be able to handle strings, dictionaries and lists. This allows you to change the key of subsections as well as for ordinary members. The return value when called on the whole subsection has to be discarded.
See the encode and decode methods for examples, including functions.
caution
You can use walk to transform the names of members of a section but you mustn’t add or delete members.
>>> config = '''[XXXXsection]
... XXXXkey = XXXXvalue'''.splitlines()
>>> cfg = ConfigObj(config)
>>> cfg
ConfigObj({'XXXXsection': {'XXXXkey': 'XXXXvalue'}})
>>> def transform(section, key):
... val = section[key]
... newkey = key.replace('XXXX', 'CLIENT1')
... section.rename(key, newkey)
... if isinstance(val, (tuple, list, dict)):
... pass
... else:
... val = val.replace('XXXX', 'CLIENT1')
... section[newkey] = val
>>> cfg.walk(transform, call_on_sections=True)
{'CLIENT1section': {'CLIENT1key': None}}
>>> cfg
ConfigObj({'CLIENT1section': {'CLIENT1key': 'CLIENT1value'}})
Write the current ConfigObj as a file
tekNico: FIXME: use StringIO instead of real files
>>> filename = a.filename
>>> a.filename = 'test.ini'
>>> a.write()
>>> a.filename = filename
>>> a == ConfigObj('test.ini', raise_errors=True)
1
>>> import os
>>> os.remove('test.ini')