2.1 Creating the parser

class ConfigParser
This class can be used to parse options from user configuration files. A single instance of this class is typically created. This single instance may be used to parse multiple configuration files and obtain multiple configuration options.

The constructor for this class is:

ConfigParser( [description][, allow_py][, formatter][, exception])

description is an optional string keyword argument and controls the introductory text placed above configuration option help text. See "Option Help" (section 2.3.4).

allow_py is an optional boolean keyword argument and when set to True, allows Python based configuraton files to be read (executed). The default is False. Enabling this feature poses a potential security hole for your application.

formatter is an optional keyword argument and controls the configuration option help text style. Set to either the IndentedHelpFormatter or TitledHelpFormatter class in the cfgparse module (or a subclass of either).

exception is an optional keyword argument and controls the how user errors are handled by the parser. If set to False or omitted, errors are written to sys.stderr and sys.exit() is called. If set to True, the ConfigParserUserError exception is raised. Otherwise set this argument to the custom exception class that should be raised.

In many applications the defaults for constructing an instance of ConfigParser are sufficient.

For example:

# file: construct.ini
retries = 10

# file: construct.py
import cfgparse
c = cfgparse.ConfigParser()
c.add_option('retries', type='int')
c.add_file('construct.ini')
opts = c.parse()
print 'Number of retries:',opts.retries

Results in:

$ python construct.py
Number of retries: 10