source: vendor/python/2.5/Doc/lib/libcfgparser.tex

Last change on this file was 3225, checked in by bird, 18 years ago

Python 2.5

File size: 11.8 KB
Line 
1\section{\module{ConfigParser} ---
2 Configuration file parser}
3
4\declaremodule{standard}{ConfigParser}
5\modulesynopsis{Configuration file parser.}
6\moduleauthor{Ken Manheimer}{klm@zope.com}
7\moduleauthor{Barry Warsaw}{bwarsaw@python.org}
8\moduleauthor{Eric S. Raymond}{esr@thyrsus.com}
9\sectionauthor{Christopher G. Petrilli}{petrilli@amber.org}
10
11This module defines the class \class{ConfigParser}.
12\indexii{.ini}{file}\indexii{configuration}{file}\index{ini file}
13\index{Windows ini file}
14The \class{ConfigParser} class implements a basic configuration file
15parser language which provides a structure similar to what you would
16find on Microsoft Windows INI files. You can use this to write Python
17programs which can be customized by end users easily.
18
19\begin{notice}[warning]
20 This library does \emph{not} interpret or write the value-type
21 prefixes used in the Windows Registry extended version of INI syntax.
22\end{notice}
23
24The configuration file consists of sections, led by a
25\samp{[section]} header and followed by \samp{name: value} entries,
26with continuations in the style of \rfc{822}; \samp{name=value} is
27also accepted. Note that leading whitespace is removed from values.
28The optional values can contain format strings which refer to other
29values in the same section, or values in a special
30\code{DEFAULT} section. Additional defaults can be provided on
31initialization and retrieval. Lines beginning with \character{\#} or
32\character{;} are ignored and may be used to provide comments.
33
34For example:
35
36\begin{verbatim}
37[My Section]
38foodir: %(dir)s/whatever
39dir=frob
40\end{verbatim}
41
42would resolve the \samp{\%(dir)s} to the value of
43\samp{dir} (\samp{frob} in this case). All reference expansions are
44done on demand.
45
46Default values can be specified by passing them into the
47\class{ConfigParser} constructor as a dictionary. Additional defaults
48may be passed into the \method{get()} method which will override all
49others.
50
51\begin{classdesc}{RawConfigParser}{\optional{defaults}}
52The basic configuration object. When \var{defaults} is given, it is
53initialized into the dictionary of intrinsic defaults. This class
54does not support the magical interpolation behavior.
55\versionadded{2.3}
56\end{classdesc}
57
58\begin{classdesc}{ConfigParser}{\optional{defaults}}
59Derived class of \class{RawConfigParser} that implements the magical
60interpolation feature and adds optional arguments to the \method{get()}
61and \method{items()} methods. The values in \var{defaults} must be
62appropriate for the \samp{\%()s} string interpolation. Note that
63\var{__name__} is an intrinsic default; its value is the section name,
64and will override any value provided in \var{defaults}.
65
66All option names used in interpolation will be passed through the
67\method{optionxform()} method just like any other option name
68reference. For example, using the default implementation of
69\method{optionxform()} (which converts option names to lower case),
70the values \samp{foo \%(bar)s} and \samp{foo \%(BAR)s} are
71equivalent.
72\end{classdesc}
73
74\begin{classdesc}{SafeConfigParser}{\optional{defaults}}
75Derived class of \class{ConfigParser} that implements a more-sane
76variant of the magical interpolation feature. This implementation is
77more predictable as well.
78% XXX Need to explain what's safer/more predictable about it.
79New applications should prefer this version if they don't need to be
80compatible with older versions of Python.
81\versionadded{2.3}
82\end{classdesc}
83
84\begin{excdesc}{NoSectionError}
85Exception raised when a specified section is not found.
86\end{excdesc}
87
88\begin{excdesc}{DuplicateSectionError}
89Exception raised if \method{add_section()} is called with the name of
90a section that is already present.
91\end{excdesc}
92
93\begin{excdesc}{NoOptionError}
94Exception raised when a specified option is not found in the specified
95section.
96\end{excdesc}
97
98\begin{excdesc}{InterpolationError}
99Base class for exceptions raised when problems occur performing string
100interpolation.
101\end{excdesc}
102
103\begin{excdesc}{InterpolationDepthError}
104Exception raised when string interpolation cannot be completed because
105the number of iterations exceeds \constant{MAX_INTERPOLATION_DEPTH}.
106Subclass of \exception{InterpolationError}.
107\end{excdesc}
108
109\begin{excdesc}{InterpolationMissingOptionError}
110Exception raised when an option referenced from a value does not exist.
111Subclass of \exception{InterpolationError}.
112\versionadded{2.3}
113\end{excdesc}
114
115\begin{excdesc}{InterpolationSyntaxError}
116Exception raised when the source text into which substitutions are
117made does not conform to the required syntax.
118Subclass of \exception{InterpolationError}.
119\versionadded{2.3}
120\end{excdesc}
121
122\begin{excdesc}{MissingSectionHeaderError}
123Exception raised when attempting to parse a file which has no section
124headers.
125\end{excdesc}
126
127\begin{excdesc}{ParsingError}
128Exception raised when errors occur attempting to parse a file.
129\end{excdesc}
130
131\begin{datadesc}{MAX_INTERPOLATION_DEPTH}
132The maximum depth for recursive interpolation for \method{get()} when
133the \var{raw} parameter is false. This is relevant only for the
134\class{ConfigParser} class.
135\end{datadesc}
136
137
138\begin{seealso}
139 \seemodule{shlex}{Support for a creating \UNIX{} shell-like
140 mini-languages which can be used as an alternate
141 format for application configuration files.}
142\end{seealso}
143
144
145\subsection{RawConfigParser Objects \label{RawConfigParser-objects}}
146
147\class{RawConfigParser} instances have the following methods:
148
149\begin{methoddesc}{defaults}{}
150Return a dictionary containing the instance-wide defaults.
151\end{methoddesc}
152
153\begin{methoddesc}{sections}{}
154Return a list of the sections available; \code{DEFAULT} is not
155included in the list.
156\end{methoddesc}
157
158\begin{methoddesc}{add_section}{section}
159Add a section named \var{section} to the instance. If a section by
160the given name already exists, \exception{DuplicateSectionError} is
161raised.
162\end{methoddesc}
163
164\begin{methoddesc}{has_section}{section}
165Indicates whether the named section is present in the
166configuration. The \code{DEFAULT} section is not acknowledged.
167\end{methoddesc}
168
169\begin{methoddesc}{options}{section}
170Returns a list of options available in the specified \var{section}.
171\end{methoddesc}
172
173\begin{methoddesc}{has_option}{section, option}
174If the given section exists, and contains the given option,
175return \constant{True}; otherwise return \constant{False}.
176\versionadded{1.6}
177\end{methoddesc}
178
179\begin{methoddesc}{read}{filenames}
180Attempt to read and parse a list of filenames, returning a list of filenames
181which were successfully parsed. If \var{filenames} is a string or
182Unicode string, it is treated as a single filename.
183If a file named in \var{filenames} cannot be opened, that file will be
184ignored. This is designed so that you can specify a list of potential
185configuration file locations (for example, the current directory, the
186user's home directory, and some system-wide directory), and all
187existing configuration files in the list will be read. If none of the
188named files exist, the \class{ConfigParser} instance will contain an
189empty dataset. An application which requires initial values to be
190loaded from a file should load the required file or files using
191\method{readfp()} before calling \method{read()} for any optional
192files:
193
194\begin{verbatim}
195import ConfigParser, os
196
197config = ConfigParser.ConfigParser()
198config.readfp(open('defaults.cfg'))
199config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
200\end{verbatim}
201\versionchanged[Returns list of successfully parsed filenames]{2.4}
202\end{methoddesc}
203
204\begin{methoddesc}{readfp}{fp\optional{, filename}}
205Read and parse configuration data from the file or file-like object in
206\var{fp} (only the \method{readline()} method is used). If
207\var{filename} is omitted and \var{fp} has a \member{name} attribute,
208that is used for \var{filename}; the default is \samp{<???>}.
209\end{methoddesc}
210
211\begin{methoddesc}{get}{section, option}
212Get an \var{option} value for the named \var{section}.
213\end{methoddesc}
214
215\begin{methoddesc}{getint}{section, option}
216A convenience method which coerces the \var{option} in the specified
217\var{section} to an integer.
218\end{methoddesc}
219
220\begin{methoddesc}{getfloat}{section, option}
221A convenience method which coerces the \var{option} in the specified
222\var{section} to a floating point number.
223\end{methoddesc}
224
225\begin{methoddesc}{getboolean}{section, option}
226A convenience method which coerces the \var{option} in the specified
227\var{section} to a Boolean value. Note that the accepted values
228for the option are \code{"1"}, \code{"yes"}, \code{"true"}, and \code{"on"},
229which cause this method to return \code{True}, and \code{"0"}, \code{"no"},
230\code{"false"}, and \code{"off"}, which cause it to return \code{False}. These
231string values are checked in a case-insensitive manner. Any other value will
232cause it to raise \exception{ValueError}.
233\end{methoddesc}
234
235\begin{methoddesc}{items}{section}
236Return a list of \code{(\var{name}, \var{value})} pairs for each
237option in the given \var{section}.
238\end{methoddesc}
239
240\begin{methoddesc}{set}{section, option, value}
241If the given section exists, set the given option to the specified
242value; otherwise raise \exception{NoSectionError}. While it is
243possible to use \class{RawConfigParser} (or \class{ConfigParser} with
244\var{raw} parameters set to true) for \emph{internal} storage of
245non-string values, full functionality (including interpolation and
246output to files) can only be achieved using string values.
247\versionadded{1.6}
248\end{methoddesc}
249
250\begin{methoddesc}{write}{fileobject}
251Write a representation of the configuration to the specified file
252object. This representation can be parsed by a future \method{read()}
253call.
254\versionadded{1.6}
255\end{methoddesc}
256
257\begin{methoddesc}{remove_option}{section, option}
258Remove the specified \var{option} from the specified \var{section}.
259If the section does not exist, raise \exception{NoSectionError}.
260If the option existed to be removed, return \constant{True};
261otherwise return \constant{False}.
262\versionadded{1.6}
263\end{methoddesc}
264
265\begin{methoddesc}{remove_section}{section}
266Remove the specified \var{section} from the configuration.
267If the section in fact existed, return \code{True}.
268Otherwise return \code{False}.
269\end{methoddesc}
270
271\begin{methoddesc}{optionxform}{option}
272Transforms the option name \var{option} as found in an input file or
273as passed in by client code to the form that should be used in the
274internal structures. The default implementation returns a lower-case
275version of \var{option}; subclasses may override this or client code
276can set an attribute of this name on instances to affect this
277behavior. Setting this to \function{str()}, for example, would make
278option names case sensitive.
279\end{methoddesc}
280
281
282\subsection{ConfigParser Objects \label{ConfigParser-objects}}
283
284The \class{ConfigParser} class extends some methods of the
285\class{RawConfigParser} interface, adding some optional arguments.
286
287\begin{methoddesc}{get}{section, option\optional{, raw\optional{, vars}}}
288Get an \var{option} value for the named \var{section}. All the
289\character{\%} interpolations are expanded in the return values, based
290on the defaults passed into the constructor, as well as the options
291\var{vars} provided, unless the \var{raw} argument is true.
292\end{methoddesc}
293
294\begin{methoddesc}{items}{section\optional{, raw\optional{, vars}}}
295Return a list of \code{(\var{name}, \var{value})} pairs for each
296option in the given \var{section}. Optional arguments have the
297same meaning as for the \method{get()} method.
298\versionadded{2.3}
299\end{methoddesc}
300
301
302\subsection{SafeConfigParser Objects \label{SafeConfigParser-objects}}
303
304The \class{SafeConfigParser} class implements the same extended
305interface as \class{ConfigParser}, with the following addition:
306
307\begin{methoddesc}{set}{section, option, value}
308If the given section exists, set the given option to the specified
309value; otherwise raise \exception{NoSectionError}. \var{value} must
310be a string (\class{str} or \class{unicode}); if not,
311\exception{TypeError} is raised.
312\versionadded{2.4}
313\end{methoddesc}
Note: See TracBrowser for help on using the repository browser.