configparser.ConfigParser

class configparser.ConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation(), converters={})

The main configuration parser. When defaults is given, it is initialized into the dictionary of intrinsic defaults. When dict_type is given, it will be used to create the dictionary objects for the list of sections, for the options within a section, and for the default values.

When delimiters is given, it is used as the set of substrings that divide keys from values. When comment_prefixes is given, it will be used as the set of substrings that prefix comments in otherwise empty lines. Comments can be indented. When inline_comment_prefixes is given, it will be used as the set of substrings that prefix comments in non-empty lines.

When strict is True (the default), the parser won’t allow for any section or option duplicates while reading from a single source (file, string or dictionary), raising DuplicateSectionError or DuplicateOptionError. When empty_lines_in_values is False (default: True), each empty line marks the end of an option. Otherwise, internal empty lines of a multiline option are kept as part of the value. When allow_no_value is True (default: False), options without values are accepted; the value held for these is None and they are serialized without the trailing delimiter.

When default_section is given, it specifies the name for the special section holding default values for other sections and interpolation purposes (normally named "DEFAULT"). This value can be retrieved and changed on runtime using the default_section instance attribute.

Interpolation behaviour may be customized by providing a custom handler through the interpolation argument. None can be used to turn off interpolation completely, ExtendedInterpolation() provides a more advanced variant inspired by zc.buildout. More on the subject in the dedicated documentation section.

All option names used in interpolation will be passed through the optionxform() method just like any other option name reference. For example, using the default implementation of optionxform() (which converts option names to lower case), the values foo %(bar)s and foo %(BAR)s are equivalent.

When converters is given, it should be a dictionary where each key represents the name of a type converter and each value is a callable implementing the conversion from string to the desired datatype. Every converter gets its own corresponding get*() method on the parser object and section proxies.

Changed in version 3.1: The default dict_type is collections.OrderedDict.

Changed in version 3.2: allow_no_value, delimiters, comment_prefixes, strict, empty_lines_in_values, default_section and interpolation were added.

Changed in version 3.5: The converters argument was added.

defaults()

Return a dictionary containing the instance-wide defaults.

sections()

Return a list of the sections available; the default section is not included in the list.

add_section(section)

Add a section named section to the instance. If a section by the given name already exists, DuplicateSectionError is raised. If the default section name is passed, ValueError is raised. The name of the section must be a string; if not, TypeError is raised.

Changed in version 3.2: Non-string section names raise TypeError.

has_section(section)

Indicates whether the named section is present in the configuration. The default section is not acknowledged.

options(section)

Return a list of options available in the specified section.

has_option(section, option)

If the given section exists, and contains the given option, return True; otherwise return False. If the specified section is None or an empty string, DEFAULT is assumed.

read(filenames, encoding=None)

Attempt to read and parse a list of filenames, returning a list of filenames which were successfully parsed. If filenames is a string, it is treated as a single filename. If a file named in filenames cannot be opened, that file will be ignored. This is designed so that you can specify a list of potential configuration file locations (for example, the current directory, the user’s home directory, and some system-wide directory), and all existing configuration files in the list will be read. If none of the named files exist, the ConfigParser instance will contain an empty dataset. An application which requires initial values to be loaded from a file should load the required file or files using read_file() before calling read() for any optional files:

import configparser, os

config = configparser.ConfigParser()
config.read_file(open('defaults.cfg'))
config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
            encoding='cp1250')

New in version 3.2: The encoding parameter. Previously, all files were read using the default encoding for open().

read_file(f, source=None)

Read and parse configuration data from f which must be an iterable yielding Unicode strings (for example files opened in text mode).

Optional argument source specifies the name of the file being read. If not given and f has a name attribute, that is used for source; the default is '<???>'.

New in version 3.2: Replaces readfp().

read_string(string, source='')

Parse configuration data from a string.

Optional argument source specifies a context-specific name of the string passed. If not given, '<string>' is used. This should commonly be a filesystem path or a URL.

New in version 3.2.

read_dict(dictionary, source='')

Load configuration from any object that provides a dict-like items() method. Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type preserves order, sections and their keys will be added in order. Values are automatically converted to strings.

Optional argument source specifies a context-specific name of the dictionary passed. If not given, <dict> is used.

This method can be used to copy state between parsers.

New in version 3.2.

get(section, option, *, raw=False, vars=None[, fallback])

Get an option value for the named section. If vars is provided, it must be a dictionary. The option is looked up in vars (if provided), section, and in DEFAULTSECT in that order. If the key is not found and fallback is provided, it is used as a fallback value. None can be provided as a fallback value.

All the '%' interpolations are expanded in the return values, unless the raw argument is true. Values for interpolation keys are looked up in the same manner as the option.

Changed in version 3.2: Arguments raw, vars and fallback are keyword only to protect users from trying to use the third argument as the fallback fallback (especially when using the mapping protocol).

getint(section, option, *, raw=False, vars=None[, fallback])

A convenience method which coerces the option in the specified section to an integer. See get() for explanation of raw, vars and fallback.

getfloat(section, option, *, raw=False, vars=None[, fallback])

A convenience method which coerces the option in the specified section to a floating point number. See get() for explanation of raw, vars and fallback.

getboolean(section, option, *, raw=False, vars=None[, fallback])

A convenience method which coerces the option in the specified section to a Boolean value. Note that the accepted values for the option are '1', 'yes', 'true', and 'on', which cause this method to return True, and '0', 'no', 'false', and 'off', which cause it to return False. These string values are checked in a case-insensitive manner. Any other value will cause it to raise ValueError. See get() for explanation of raw, vars and fallback.

items(raw=False, vars=None)
items(section, raw=False, vars=None)

When section is not given, return a list of section_name, section_proxy pairs, including DEFAULTSECT.

Otherwise, return a list of name, value pairs for the options in the given section. Optional arguments have the same meaning as for the get() method.

Changed in version 3.2: Items present in vars no longer appear in the result. The previous behaviour mixed actual parser options with variables provided for interpolation.

set(section, option, value)

If the given section exists, set the given option to the specified value; otherwise raise NoSectionError. option and value must be strings; if not, TypeError is raised.

write(fileobject, space_around_delimiters=True)

Write a representation of the configuration to the specified file object, which must be opened in text mode (accepting strings). This representation can be parsed by a future read() call. If space_around_delimiters is true, delimiters between keys and values are surrounded by spaces.

remove_option(section, option)

Remove the specified option from the specified section. If the section does not exist, raise NoSectionError. If the option existed to be removed, return True; otherwise return False.

remove_section(section)

Remove the specified section from the configuration. If the section in fact existed, return True. Otherwise return False.

optionxform(option)

Transforms the option name option as found in an input file or as passed in by client code to the form that should be used in the internal structures. The default implementation returns a lower-case version of option; subclasses may override this or client code can set an attribute of this name on instances to affect this behavior.

You don’t need to subclass the parser to use this method, you can also set it on an instance, to a function that takes a string argument and returns a string. Setting it to str, for example, would make option names case sensitive:

cfgparser = ConfigParser()
cfgparser.optionxform = str

Note that when reading configuration files, whitespace around the option names is stripped before optionxform() is called.

readfp(fp, filename=None)

Deprecated since version 3.2: Use read_file() instead.

Changed in version 3.2: readfp() now iterates on f instead of calling f.readline().

For existing code calling readfp() with arguments which don’t support iteration, the following generator may be used as a wrapper around the file-like object:

def readline_generator(f):
    line = f.readline()
    while line:
        yield line
        line = f.readline()

Instead of parser.readfp(f) use parser.read_file(readline_generator(f)).

doc_python
2016-10-07 17:29:10
Comments
Leave a Comment

Please login to continue.