2.5 Parsing and Obtaining Options

Configuration file options settings may be obtained either all at once or one at a time. The parse() method may be used for obtaining all the option settings all at once and returns the options bundled in a single object as attributes. If errors are found, appropriate help text will be made available (either an exception is raised or sys.exit() is called dependent on exception argument when instantiating ConfigParser). This allows errors to be reported to the user up front.

parse( [optparser][, args])

optparse is an optional keyword argument and is used to pass in an instance of a command line option parser with which the configuration option parser is to cooperate with. Omitting this argument or setting to None avoids interfacing to a command line option parser. When used, the parse() method will return a tuple of the bundled options object and the command line arguments. The bundled options object will contain the options from both the command line parser and the configuration files. Presence of this option will also allow enable the use of other cooperation features documented in "Command line cooperation" (section 3).

args is an optional keyword argument and are the arguments to be parsed by the command line option parser. Omitting this argument or setting to None causes arguments in sys.argv (from the command line) to be utilized.

An alternative method is to get the options as they are needed using the get() method of the object returned by the add_option() method.

get( [keys][, errors])

keys is an optional keyword argument and is used to pass in additional keys to use obtain the option setting. See "Keys" (section 6) for more information.

errors is an optional keyword argument. If omitted or set to None any errors will cause appropriate help text will be made available (either an exception is raised or sys.exit() is called dependent on exception argument when instantiating ConfigParser). Otherwise pass a list and help text describing the error will appended into the list.

For example:

# file: parsing.ini
retries = 10

And script:

# file: parsing.py
import cfgparse
c = cfgparse.ConfigParser()
c.add_file('parsing.ini')

retries = c.add_option('retries', type='int')
print retries.get()

timeout = c.add_option('timeout', type='int')
print timeout.get()

Results in:

$ python parsing.py
10
ERROR: Configuration File Parser

Option: timeout
No valid default found.
keys=DEFAULT