The main configuration parser. When
defaults
is given, it is initialized into the dictionary of intrinsic defaults. When
dict_type
is given, it will be used to create the dictionary objects for the list of sections, for the options within a section, and for the default values.
当
delimiters
is given, it is used as the set of substrings that divide keys from values. When
comment_prefixes
is given, it will be used as the set of substrings that prefix comments in otherwise empty lines. Comments can be indented. When
inline_comment_prefixes
is given, it will be used as the set of substrings that prefix comments in non-empty lines.
当
strict
is
True
(the default), the parser won’t allow for any section or option duplicates while reading from a single source (file, string or dictionary), raising
DuplicateSectionError
or
DuplicateOptionError
。当
empty_lines_in_values
is
False
(default:
True
), each empty line marks the end of an option. Otherwise, internal empty lines of a multiline option are kept as part of the value. When
allow_no_value
is
True
(default:
False
), options without values are accepted; the value held for these is
None
and they are serialized without the trailing delimiter.
当
default_section
is given, it specifies the name for the special section holding default values for other sections and interpolation purposes (normally named
"DEFAULT"
). This value can be retrieved and changed at runtime using the
default_section
instance attribute. This won’t re-evaluate an already parsed config file, but will be used when writing parsed settings to a new config file.
Interpolation behaviour may be customized by providing a custom handler through the
interpolation
自变量。
None
can be used to turn off interpolation completely,
ExtendedInterpolation()
provides a more advanced variant inspired by
zc.buildout
. More on the subject in the
dedicated documentation section
.
All option names used in interpolation will be passed through the
optionxform()
method just like any other option name reference. For example, using the default implementation of
optionxform()
(which converts option names to lower case), the values
foo %(bar)s
and
foo
%(BAR)s
are equivalent.
当
converters
is given, it should be a dictionary where each key represents the name of a type converter and each value is a callable implementing the conversion from string to the desired datatype. Every converter gets its own corresponding
get*()
method on the parser object and section proxies.
当
allow_unnamed_section
is
True
(default:
False
), the first section name can be omitted. See the
“Unnamed Sections” section
.
It is possible to read several configurations into a single
ConfigParser
, where the most recently added configuration has the highest priority. Any conflicting keys are taken from the more recent configuration while the previously existing keys are retained. The example below reads in an
override.ini
file, which will override any conflicting keys from the
example.ini
文件。
[DEFAULT]
ServerAliveInterval = -1
>>> config_override = configparser.ConfigParser()
>>> config_override['DEFAULT'] = {'ServerAliveInterval': '-1'}
>>> with open('override.ini', 'w') as configfile:
... config_override.write(configfile)
...
>>> config_override = configparser.ConfigParser()
>>> config_override.read(['example.ini', 'override.ini'])
['example.ini', 'override.ini']
>>> print(config_override.get('DEFAULT', 'ServerAliveInterval'))
-1
3.1 版改变:
默认
dict_type
is
collections.OrderedDict
.
3.2 版改变:
allow_no_value
,
delimiters
,
comment_prefixes
,
strict
,
empty_lines_in_values
,
default_section
and
interpolation
被添加。
3.5 版改变:
The
converters
自变量被添加。
3.7 版改变:
The
defaults
argument is read with
read_dict()
, providing consistent behavior across the parser: non-string keys and values are implicitly converted to strings.
3.8 版改变:
默认
dict_type
is
dict
, since it now preserves insertion order.
Changed in version 3.13:
引发
MultilineContinuationError
当
allow_no_value
is
True
, and a key without a value is continued with an indented line.
Changed in version 3.13:
The
allow_unnamed_section
自变量被添加。
-
defaults
(
)
¶
-
Return a dictionary containing the instance-wide defaults.
-
sections
(
)
¶
-
Return a list of the sections available; the
default section
is not included in the list.
-
add_section
(
section
)
¶
-
Add a section named
section
to the instance. If a section by the given name already exists,
DuplicateSectionError
is raised. If the
default section
name is passed,
ValueError
is raised. The name of the section must be a string; if not,
TypeError
被引发。
3.2 版改变:
Non-string section names raise
TypeError
.
-
has_section
(
section
)
¶
-
Indicates whether the named
section
is present in the configuration. The
default section
is not acknowledged.
-
选项
(
section
)
¶
-
Return a list of options available in the specified
section
.
-
has_option
(
section
,
option
)
¶
-
若给定
section
exists, and contains the given
option
,返回
True
;否则返回
False
。若指定
section
is
None
or an empty string, DEFAULT is assumed.
-
read
(
filenames
,
encoding
=
None
)
¶
-
Attempt to read and parse an iterable of filenames, returning a list of filenames which were successfully parsed.
若
filenames
is a string, a
bytes
对象或
像路径对象
, it is treated as a single filename. If a file named in
filenames
cannot be opened, that file will be ignored. This is designed so that you can specify an iterable of potential configuration file locations (for example, the current directory, the user’s home directory, and some system-wide directory), and all existing configuration files in the iterable will be read.
If none of the named files exist, the
ConfigParser
instance will contain an empty dataset. An application which requires initial values to be loaded from a file should load the required file or files using
read_file()
before calling
read()
for any optional files:
import configparser, os
config = configparser.ConfigParser()
config.read_file(open('defaults.cfg'))
config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
encoding='cp1250')
3.2 版改变:
添加
encoding
parameter. Previously, all files were read using the default encoding for
open()
.
3.6.1 版改变:
The
filenames
参数接受
像路径对象
.
3.7 版改变:
The
filenames
参数接受
bytes
对象。
-
read_file
(
f
,
source
=
None
)
¶
Read and parse configuration data from
f
which must be an iterable yielding Unicode strings (for example files opened in text mode).
可选自变量
source
specifies the name of the file being read. If not given and
f
拥有
name
attribute, that is used for
source
; the default is
'<???>'
.
Added in version 3.2:
替换
readfp()
.
-
read_string
(
string
,
source
=
'<string>'
)
¶
-
Parse configuration data from a string.
可选自变量
source
specifies a context-specific name of the string passed. If not given,
'<string>'
is used. This should commonly be a filesystem path or a URL.
Added in version 3.2.
-
read_dict
(
dictionary
,
source
=
'<dict>'
)
¶
-
Load configuration from any object that provides a dict-like
items()
method. Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type preserves order, sections and their keys will be added in order. Values are automatically converted to strings.
可选自变量
source
specifies a context-specific name of the dictionary passed. If not given,
<dict>
被使用。
This method can be used to copy state between parsers.
Added in version 3.2.
-
get
(
section
,
option
,
*
,
raw=False
,
vars=None
[
,
fallback
]
)
¶
-
Get an
option
value for the named
section
。若
vars
is provided, it must be a dictionary. The
option
is looked up in
vars
(if provided),
section
, and in
DEFAULTSECT
in that order. If the key is not found and
fallback
is provided, it is used as a fallback value.
None
can be provided as a
fallback
值。
All the
'%'
interpolations are expanded in the return values, unless the
raw
argument is true. Values for interpolation keys are looked up in the same manner as the option.
3.2 版改变:
自变量
raw
,
vars
and
fallback
are keyword only to protect users from trying to use the third argument as the
fallback
fallback (especially when using the mapping protocol).
-
getint
(
section
,
option
,
*
,
raw=False
,
vars=None
[
,
fallback
]
)
¶
-
A convenience method which coerces the
option
以指定
section
to an integer. See
get()
for explanation of
raw
,
vars
and
fallback
.
-
getfloat
(
section
,
option
,
*
,
raw=False
,
vars=None
[
,
fallback
]
)
¶
-
A convenience method which coerces the
option
以指定
section
to a floating-point number. See
get()
for explanation of
raw
,
vars
and
fallback
.
-
getboolean
(
section
,
option
,
*
,
raw=False
,
vars=None
[
,
fallback
]
)
¶
-
A convenience method which coerces the
option
以指定
section
to a Boolean value. Note that the accepted values for the option are
'1'
,
'yes'
,
'true'
,和
'on'
, which cause this method to return
True
,和
'0'
,
'no'
,
'false'
,和
'off'
, which cause it to return
False
. These string values are checked in a case-insensitive manner. Any other value will cause it to raise
ValueError
。见
get()
for explanation of
raw
,
vars
and
fallback
.
-
items
(
raw
=
False
,
vars
=
None
)
¶
-
items
(
section
,
raw
=
False
,
vars
=
None
)
-
当
section
is not given, return a list of
section_name
,
section_proxy
pairs, including DEFAULTSECT.
Otherwise, return a list of
name
,
value
pairs for the options in the given
section
. Optional arguments have the same meaning as for the
get()
方法。
3.8 版改变:
Items present in
vars
no longer appear in the result. The previous behaviour mixed actual parser options with variables provided for interpolation.
-
set
(
section
,
option
,
值
)
¶
-
If the given section exists, set the given option to the specified value; otherwise raise
NoSectionError
.
option
and
value
must be strings; if not,
TypeError
被引发。
-
write
(
fileobject
,
space_around_delimiters
=
True
)
¶
-
Write a representation of the configuration to the specified
文件对象
, which must be opened in text mode (accepting strings). This representation can be parsed by a future
read()
call. If
space_around_delimiters
is true, delimiters between keys and values are surrounded by spaces.
注意
Comments in the original configuration file are not preserved when writing the configuration back. What is considered a comment, depends on the given values for
comment_prefix
and
inline_comment_prefix
.
-
remove_option
(
section
,
option
)
¶
-
Remove the specified
option
从指定
section
. If the section does not exist, raise
NoSectionError
. If the option existed to be removed, return
True
;否则返回
False
.
-
remove_section
(
section
)
¶
-
Remove the specified
section
from the configuration. If the section in fact existed, return
True
. Otherwise return
False
.
-
optionxform
(
option
)
¶
-
Transforms the option name
option
as found in an input file or as passed in by client code to the form that should be used in the internal structures. The default implementation returns a lower-case version of
option
; subclasses may override this or client code can set an attribute of this name on instances to affect this behavior.
You don’t need to subclass the parser to use this method, you can also set it on an instance, to a function that takes a string argument and returns a string. Setting it to
str
, for example, would make option names case sensitive:
cfgparser = ConfigParser()
cfgparser.optionxform = str
Note that when reading configuration files, whitespace around the option names is stripped before
optionxform()
被调用。