Package grizzled :: Module config
[hide private]
[frames] | no frames]

Module config

source code

Introduction

Based on the standard Python ConfigParser module, this module provides an enhanced configuration parser capabilities. Configuration is a drop-in replacement for ConfigParser.

A configuration file is broken into sections, and each section is introduced by a section name in brackets. For example:

[main]
installationDirectory=/usr/local/foo
programDirectory: /usr/local/foo/programs

[search]
searchCommand: find /usr/local/foo -type f -name "*.class"

[display]
searchFailedMessage=Search failed, sorry.

Section Name Syntax

A section name can consist of alphabetics, numerics, underscores and periods. There can be any amount of whitespace before and after the brackets in a section name; the whitespace is ignored.

Variable Syntax

Each section contains zero or more variable settings.

Variable Substitution

A variable value can interpolate the values of other variables, using a variable substitution syntax. The general form of a variable reference is ${section_name:var_name}.

Default values

You can also specify a default value for a variable, using this syntax:

${foo?default}
${section:foo?default}

That is, the sequence ?default after a variable name specifies the default value if the variable has no value. (Normally, if a variable has no value, it is replaced with an empty string.) Defaults can be useful, for instance, to allow overrides from the environment. The following example defines a log file directory that defaults to "/tmp", unless environment variable LOGDIR is set to a non-empty value:

logDirectory: ${env:LOGDIR?/var/log}

Special section names

The section names "env", and "program" are reserved for special pseudosections.

The env pseudosection

The "env" pseudosection is used to interpolate values from the environment. On UNIX systems, for instance, ${env:HOME} substitutes home directory of the current user. On some versions of Windows, ${env:USERNAME} will substitute the name of the user.

Note: On UNIX systems, environment variable names are typically case-sensitive; for instance, ${env:USER} and ${env:user} refer to different environment variables. On Windows systems, environment variable names are typically case-insensitive; ${env:USERNAME} and ${env:username} are equivalent.

The program pseudosection

The "program" pseudosection is a placeholder for various special variables provided by the Configuration class. Those variables are:

cwd
The current working directory. Thus, ${program:cwd} will substitute the working directory, using the appropriate system-specific file separator (e.g., "/" on Unix, "" on Windows).
name
The calling program name. Equivalent to the Python expression os.path.basename(sys.argv[0])
now
The current time, formatted using the time.strftime() format "%Y-%m-%d %H:%M:%S" (e.g., "2008-03-03 16:15:27")

Includes

A special include directive permits inline inclusion of another configuration file. The include directive takes two forms:

%include "path"
%include "URL"

For example:

%include "/home/bmc/mytools/common.cfg"
%include "http://configs.example.com/mytools/common.cfg"

The included file may contain any content that is valid for this parser. It may contain just variable definitions (i.e., the contents of a section, without the section header), or it may contain a complete configuration file, with individual sections.

Note: Attempting to include a file from itself, either directly or indirectly, will cause the parser to throw an exception.

Replacing ConfigParser

You can use this class anywhere you would use the standard Python ConfigParser class. Thus, to change a piece of code to use enhanced configuration, you might change this:

import ConfigParser

config = ConfigParser.SafeConfigParser()
config.read(configPath)

to this:

from grizzled.config import Configuration

config = Configuration()
config.read(configPath)

Sometimes, however, you have to use an API that expects a path to a configuration file that can only be parsed with the (unenhanced) ConfigParser class. In that case, you simply use the preprocess() method:

import logging
from grizzled import config

logging.config.fileConfig(config.preprocess(pathToConfig))

That will preprocess the enhanced configuration file, producing a file that is suitable for parsing by the standard Python config module.

Classes [hide private]
  NoOptionError
A requested option was not found.
  NoSectionError
Raised when no section matches a requested option.
  NoVariableError
Thrown when a configuration file attempts to substitute a nonexistent variable, and the Configuration object was instantiated with strict_substitution set to True.
  Configuration
Configuration file parser.
  _ConfigTemplate
Subclass of string.Template that handles our configuration variable reference syntax.
  _ConfigDict
Dictionary that knows how to dereference variables within a parsed config.
Functions [hide private]
string
preprocess(file_or_url, defaults=None)
This function preprocesses a file or URL for a configuration file, processing all includes and substituting all variables.
source code
Variables [hide private]
  log = logging.getLogger('grizzled.config')
  SECTION_OPTION_DELIM = ':'
  SECTION_NAME_PATTERN = '([_.a-zA-Z][_.a-zA-Z0-9]+)'
  VARIABLE_NAME_PATTERN = '([_a-zA-Z][_a-zA-Z0-9]+)(\\?[^}]+)?'
  VARIABLE_REF_PATTERN = '([_.a-zA-Z][_.a-zA-Z0-9]+):([_a-zA-Z][...
  SIMPLE_VARIABLE_REF_PATTERN = '\\$\\{([_a-zA-Z][_a-zA-Z0-9]+)(...
  ENV_SECTION = 'env'
  PROGRAM_SECTION = 'program'
  __package__ = None
hash(x)
Function Details [hide private]

preprocess(file_or_url, defaults=None)

source code 

This function preprocesses a file or URL for a configuration file, processing all includes and substituting all variables. It writes a new configuration file to a temporary file (or specified output file). The new configuration file can be read by a standard ConfigParser object. Thus, this method is useful when you have an extended configuration file that must be passed to a function or object that can only read a standard ConfigParser file.

For example, here's how you might use the Python logging API with an extended configuration file:

from grizzled.config import Configuration
import logging

logging.config.fileConfig(Configuration.preprocess('/path/to/config')
Parameters:
  • file_or_url (str) - file or URL to read and preprocess
  • defaults (dict) - defaults to pass through to the config parser
Returns: string
Path to a temporary file containing the expanded configuration. The file will be deleted when the program exits, though the caller is free to delete it sooner.

Variables Details [hide private]

VARIABLE_REF_PATTERN

Value:
'([_.a-zA-Z][_.a-zA-Z0-9]+):([_a-zA-Z][_a-zA-Z0-9]+)(\\?[^}]+)?|([_a-z\
A-Z][_a-zA-Z0-9]+)(\\?[^}]+)?'

SIMPLE_VARIABLE_REF_PATTERN

Value:
'\\$\\{([_a-zA-Z][_a-zA-Z0-9]+)(\\?[^}]+)?\\}'