1 \section{\module{ConfigParser
} ---
2 Configuration file parser
}
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
}
11 This module defines the class
\class{ConfigParser
}.
12 \indexii{.ini
}{file
}\indexii{configuration
}{file
}\index{ini file
}
13 \index{Windows ini file
}
14 The
\class{ConfigParser
} class implements a basic configuration file
15 parser language which provides a structure similar to what you would
16 find on Microsoft Windows INI files. You can use this to write Python
17 programs which can be customized by end users easily.
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.
24 The configuration file consists of sections, led by a
25 \samp{[section
]} header and followed by
\samp{name: value
} entries,
26 with continuations in the style of
\rfc{822};
\samp{name=value
} is
27 also accepted. Note that leading whitespace is removed from values.
28 The optional values can contain format strings which refer to other
29 values in the same section, or values in a special
30 \code{DEFAULT
} section. Additional defaults can be provided on
31 initialization and retrieval. Lines beginning with
\character{\#
} or
32 \character{;
} are ignored and may be used to provide comments.
38 foodir:
%(dir)s/whatever
42 would resolve the
\samp{\%(dir)s
} to the value of
43 \samp{dir
} (
\samp{frob
} in this case). All reference expansions are
46 Default values can be specified by passing them into the
47 \class{ConfigParser
} constructor as a dictionary. Additional defaults
48 may be passed into the
\method{get()
} method which will override all
51 \begin{classdesc
}{RawConfigParser
}{\optional{defaults
}}
52 The basic configuration object. When
\var{defaults
} is given, it is
53 initialized into the dictionary of intrinsic defaults. This class
54 does not support the magical interpolation behavior.
58 \begin{classdesc
}{ConfigParser
}{\optional{defaults
}}
59 Derived class of
\class{RawConfigParser
} that implements the magical
60 interpolation feature and adds optional arguments to the
\method{get()
}
61 and
\method{items()
} methods. The values in
\var{defaults
} must be
62 appropriate for the
\samp{\%()s
} string interpolation. Note that
63 \var{__name__
} is an intrinsic default; its value is the section name,
64 and will override any value provided in
\var{defaults
}.
66 All option names used in interpolation will be passed through the
67 \method{optionxform()
} method just like any other option name
68 reference. For example, using the default implementation of
69 \method{optionxform()
} (which converts option names to lower case),
70 the values
\samp{foo \%(bar)s
} and
\samp{foo \%(BAR)s
} are
74 \begin{classdesc
}{SafeConfigParser
}{\optional{defaults
}}
75 Derived class of
\class{ConfigParser
} that implements a more-sane
76 variant of the magical interpolation feature. This implementation is
77 more predictable as well.
78 % XXX Need to explain what's safer/more predictable about it.
79 New applications should prefer this version if they don't need to be
80 compatible with older versions of Python.
84 \begin{excdesc
}{NoSectionError
}
85 Exception raised when a specified section is not found.
88 \begin{excdesc
}{DuplicateSectionError
}
89 Exception raised if
\method{add_section()
} is called with the name of
90 a section that is already present.
93 \begin{excdesc
}{NoOptionError
}
94 Exception raised when a specified option is not found in the specified
98 \begin{excdesc
}{InterpolationError
}
99 Base class for exceptions raised when problems occur performing string
103 \begin{excdesc
}{InterpolationDepthError
}
104 Exception raised when string interpolation cannot be completed because
105 the number of iterations exceeds
\constant{MAX_INTERPOLATION_DEPTH
}.
106 Subclass of
\exception{InterpolationError
}.
109 \begin{excdesc
}{InterpolationMissingOptionError
}
110 Exception raised when an option referenced from a value does not exist.
111 Subclass of
\exception{InterpolationError
}.
115 \begin{excdesc
}{InterpolationSyntaxError
}
116 Exception raised when the source text into which substitutions are
117 made does not conform to the required syntax.
118 Subclass of
\exception{InterpolationError
}.
122 \begin{excdesc
}{MissingSectionHeaderError
}
123 Exception raised when attempting to parse a file which has no section
127 \begin{excdesc
}{ParsingError
}
128 Exception raised when errors occur attempting to parse a file.
131 \begin{datadesc
}{MAX_INTERPOLATION_DEPTH
}
132 The maximum depth for recursive interpolation for
\method{get()
} when
133 the
\var{raw
} parameter is false. This is relevant only for the
134 \class{ConfigParser
} class.
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.
}
145 \subsection{RawConfigParser Objects
\label{RawConfigParser-objects
}}
147 \class{RawConfigParser
} instances have the following methods:
149 \begin{methoddesc
}{defaults
}{}
150 Return a dictionary containing the instance-wide defaults.
153 \begin{methoddesc
}{sections
}{}
154 Return a list of the sections available;
\code{DEFAULT
} is not
155 included in the list.
158 \begin{methoddesc
}{add_section
}{section
}
159 Add a section named
\var{section
} to the instance. If a section by
160 the given name already exists,
\exception{DuplicateSectionError
} is
164 \begin{methoddesc
}{has_section
}{section
}
165 Indicates whether the named section is present in the
166 configuration. The
\code{DEFAULT
} section is not acknowledged.
169 \begin{methoddesc
}{options
}{section
}
170 Returns a list of options available in the specified
\var{section
}.
173 \begin{methoddesc
}{has_option
}{section, option
}
174 If the given section exists, and contains the given option,
175 return
\constant{True
}; otherwise return
\constant{False
}.
179 \begin{methoddesc
}{read
}{filenames
}
180 Attempt to read and parse a list of filenames, returning a list of filenames
181 which were successfully parsed. If
\var{filenames
} is a string or
182 Unicode string, it is treated as a single filename.
183 If a file named in
\var{filenames
} cannot be opened, that file will be
184 ignored. This is designed so that you can specify a list of potential
185 configuration file locations (for example, the current directory, the
186 user's home directory, and some system-wide directory), and all
187 existing configuration files in the list will be read. If none of the
188 named files exist, the
\class{ConfigParser
} instance will contain an
189 empty dataset. An application which requires initial values to be
190 loaded from a file should load the required file or files using
191 \method{readfp()
} before calling
\method{read()
} for any optional
195 import ConfigParser, os
197 config = ConfigParser.ConfigParser()
198 config.readfp(open('defaults.cfg'))
199 config.read(
['site.cfg', os.path.expanduser('~/.myapp.cfg')
])
201 \versionchanged[Returns list of successfully parsed filenames
]{2.4}
204 \begin{methoddesc
}{readfp
}{fp
\optional{, filename
}}
205 Read 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,
208 that is used for
\var{filename
}; the default is
\samp{<???>
}.
211 \begin{methoddesc
}{get
}{section, option
}
212 Get an
\var{option
} value for the named
\var{section
}.
215 \begin{methoddesc
}{getint
}{section, option
}
216 A convenience method which coerces the
\var{option
} in the specified
217 \var{section
} to an integer.
220 \begin{methoddesc
}{getfloat
}{section, option
}
221 A convenience method which coerces the
\var{option
} in the specified
222 \var{section
} to a floating point number.
225 \begin{methoddesc
}{getboolean
}{section, option
}
226 A convenience method which coerces the
\var{option
} in the specified
227 \var{section
} to a Boolean value. Note that the accepted values
228 for the option are
\code{"
1"
},
\code{"yes"
},
\code{"true"
}, and
\code{"on"
},
229 which 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
231 string values are checked in a case-insensitive manner. Any other value will
232 cause it to raise
\exception{ValueError
}.
235 \begin{methoddesc
}{items
}{section
}
236 Return a list of
\code{(
\var{name
},
\var{value
})
} pairs for each
237 option in the given
\var{section
}.
240 \begin{methoddesc
}{set
}{section, option, value
}
241 If the given section exists, set the given option to the specified
242 value; otherwise raise
\exception{NoSectionError
}. While it is
243 possible to use
\class{RawConfigParser
} (or
\class{ConfigParser
} with
244 \var{raw
} parameters set to true) for
\emph{internal
} storage of
245 non-string values, full functionality (including interpolation and
246 output to files) can only be achieved using string values.
250 \begin{methoddesc
}{write
}{fileobject
}
251 Write a representation of the configuration to the specified file
252 object. This representation can be parsed by a future
\method{read()
}
257 \begin{methoddesc
}{remove_option
}{section, option
}
258 Remove the specified
\var{option
} from the specified
\var{section
}.
259 If the section does not exist, raise
\exception{NoSectionError
}.
260 If the option existed to be removed, return
\constant{True
};
261 otherwise return
\constant{False
}.
265 \begin{methoddesc
}{remove_section
}{section
}
266 Remove the specified
\var{section
} from the configuration.
267 If the section in fact existed, return
\code{True
}.
268 Otherwise return
\code{False
}.
271 \begin{methoddesc
}{optionxform
}{option
}
272 Transforms the option name
\var{option
} as found in an input file or
273 as passed in by client code to the form that should be used in the
274 internal structures. The default implementation returns a lower-case
275 version of
\var{option
}; subclasses may override this or client code
276 can set an attribute of this name on instances to affect this
277 behavior. Setting this to
\function{str()
}, for example, would make
278 option names case sensitive.
282 \subsection{ConfigParser Objects
\label{ConfigParser-objects
}}
284 The
\class{ConfigParser
} class extends some methods of the
285 \class{RawConfigParser
} interface, adding some optional arguments.
287 \begin{methoddesc
}{get
}{section, option
\optional{, raw
\optional{, vars
}}}
288 Get an
\var{option
} value for the named
\var{section
}. All the
289 \character{\%
} interpolations are expanded in the return values, based
290 on the defaults passed into the constructor, as well as the options
291 \var{vars
} provided, unless the
\var{raw
} argument is true.
294 \begin{methoddesc
}{items
}{section
\optional{, raw
\optional{, vars
}}}
295 Return a list of
\code{(
\var{name
},
\var{value
})
} pairs for each
296 option in the given
\var{section
}. Optional arguments have the
297 same meaning as for the
\method{get()
} method.
302 \subsection{SafeConfigParser Objects
\label{SafeConfigParser-objects
}}
304 The
\class{SafeConfigParser
} class implements the same extended
305 interface as
\class{ConfigParser
}, with the following addition:
307 \begin{methoddesc
}{set
}{section, option, value
}
308 If the given section exists, set the given option to the specified
309 value; otherwise raise
\exception{NoSectionError
}.
\var{value
} must
310 be a string (
\class{str
} or
\class{unicode
}); if not,
311 \exception{TypeError
} is raised.