configparser --- 設定檔剖析器¶
This module provides the ConfigParser class which implements a basic
configuration language which provides a structure similar to what's found in
Microsoft Windows INI files. You can use this to write Python programs which
can be customized by end users easily.
備註
This library does not interpret or write the value-type prefixes used in the Windows Registry extended version of INI syntax.
也參考
tomllib模組TOML is a well-specified format for application configuration files. It is specifically designed to be an improved version of INI.
shlex模組Support for creating Unix shell-like mini-languages which can also be used for application configuration files.
json模組The
jsonmodule implements a subset of JavaScript syntax which is sometimes used for configuration, but does not support comments.
Quick Start¶
Let's take a very basic configuration file that looks like this:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[forge.example]
User = hg
[topsecret.server.example]
Port = 50022
ForwardX11 = no
The structure of INI files is described in the following section. Essentially, the file
consists of sections, each of which contains keys with values.
configparser classes can read and write such files. Let's start by
creating the above configuration file programmatically.
>>> import configparser
>>> config = configparser.ConfigParser()
>>> config['DEFAULT'] = {'ServerAliveInterval': '45',
... 'Compression': 'yes',
... 'CompressionLevel': '9'}
>>> config['forge.example'] = {}
>>> config['forge.example']['User'] = 'hg'
>>> config['topsecret.server.example'] = {}
>>> topsecret = config['topsecret.server.example']
>>> topsecret['Port'] = '50022' # mutates the parser
>>> topsecret['ForwardX11'] = 'no' # same here
>>> config['DEFAULT']['ForwardX11'] = 'yes'
>>> with open('example.ini', 'w') as configfile:
... config.write(configfile)
...
As you can see, we can treat a config parser much like a dictionary. There are differences, outlined later, but the behavior is very close to what you would expect from a dictionary.
Now that we have created and saved a configuration file, let's read it back and explore the data it holds.
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['forge.example', 'topsecret.server.example']
>>> 'forge.example' in config
True
>>> 'python.org' in config
False
>>> config['forge.example']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.example']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
'50022'
>>> for key in config['forge.example']:
... print(key)
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['forge.example']['ForwardX11']
'yes'
As we can see above, the API is pretty straightforward. The only bit of magic
involves the DEFAULT section which provides default values for all other
sections [1]. Note also that keys in sections are
case-insensitive and stored in lowercase [1].
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 file.
[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
This behaviour is equivalent to a ConfigParser.read() call with several
files passed to the filenames parameter.
Supported Datatypes¶
Config parsers do not guess datatypes of values in configuration files, always storing them internally as strings. This means that if you need other datatypes, you should convert on your own:
>>> int(topsecret['Port'])
50022
>>> float(topsecret['CompressionLevel'])
9.0
Since this task is so common, config parsers provide a range of handy getter
methods to handle integers, floats and booleans. The last one is the most
interesting because simply passing the value to bool() would do no good
since bool('False') is still True. This is why config parsers also
provide getboolean(). This method is case-insensitive and
recognizes Boolean values from