configparser --- èšå®ãã¡ã€ã«ã®ããŒãµãŒÂ¶
ãœãŒã¹ã³ãŒã: Lib/configparser.py
ãã®ã¢ãžã¥ãŒã«ã¯ã Microsoft Windows ã® INI ãã¡ã€ã«ã«äŒŒãæ§é ãæã£ãããŒã·ãã¯ãªèšå®çšèšèªãå®è£
ãã ConfigParser ã¯ã©ã¹ãæäŸããŸãããã®ã¯ã©ã¹ã䜿ã£ãŠãŠãŒã¶ãŒãç°¡åã«ã«ã¹ã¿ãã€ãºã§ãã Python ããã°ã©ã ãäœãããšãã§ããŸãã
泚é
ãã®ã©ã€ãã©ãªã§ã¯ãWindowsã®ã¬ãžã¹ããªçšã«æ¡åŒµããã INI ææ³ã¯ãµããŒã ããŠããŸãã ã
åè
- ã¢ãžã¥ãŒã«
tomllib TOML is a well-specified format for application configuration files. It is specifically designed to be an improved version of INI.
shlexã¢ãžã¥ãŒã«ã¢ããªã±ãŒã·ã§ã³èšå®ãã¡ã€ã«ã«ã䜿ãããUnix ã·ã§ã«ã«äŒŒãããèšèªã®äœæãæ¯æŽããŸãã
jsonã¢ãžã¥ãŒã«The
jsonmodule implements a subset of JavaScript syntax which is sometimes used for configuration, but does not support comments.
ã¯ã€ãã¯ã¹ã¿ãŒã¶
次ã®ãããªãéåžžã«ç°¡åãªèšå®ãã¡ã€ã«ãäŸã«èããŸããã:
[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)
...
ãã®äŸã§ãããããã«ãconfig parser ã¯èŸæžã®ããã«æ±ãããšãã§ããŸããèŸæžãšã®éã㯠åŸã« 説æããŸããããã®ã€ã³ã¿ãŒãã§ã€ã¹ã¯èŸæžã«å¯ŸããŠæåŸ ããã®ãšãšãŠãè¿ãåäœãããŸãã
ããã§èšå®ãã¡ã€ã«ãäœæããŠä¿åã§ããŸãããæ¬¡ã¯ãããèªã¿èŸŒã¿çŽããŠãäžã®ããŒã¿ãåãåºããŠã¿ãŸãããã
>>> 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'
äžã®äŸãããããããã«ãAPI ã¯ãšãŠãçŽæçã§ããå¯äžã®éè¡ã¯ãDEFAULT ã»ã¯ã·ã§ã³ãä»ã®å
šãŠã®ã»ã¯ã·ã§ã³ã®ããã®ããã©ã«ãå€ãæäŸããŠããããšã§ã [1]ã ãŸããã»ã¯ã·ã§ã³å
ã®åããŒã¯å€§æåå°æåãåºå¥ãããå
šãŠå°æåã§ä¿åãããŠããããšã«ã泚æããŠãã ãã [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.
ãµããŒããããããŒã¿å¶
Config parser ã¯å€ã®ããŒã¿åã«ã€ããŠäœãæšè«ãããåžžã«æååã®ãŸãŸå éšã«ä¿åããŸããä»ã®ããŒã¿åãå¿ èŠãªå Žåã¯èªåã§å€æããå¿ èŠããããŸã:
>>> int(topsecret['Port'])
50022
>>> float(topsecret['CompressionLevel'])
9.0
ãã®ã¿ã¹ã¯ã¯ãšãŠãäžè¬çãªãããèšå®ããŒãµãŒã§ã¯æŽæ°ãæµ®åå°æ°ç¹æ°ãçåœå€ãæ±ãããã®æé ãªã²ãã¿ãŒã¡ãœãããæäŸãããŠããŸããçåœå€ã®æ±ãã¯äžççžã§ã¯ãããŸãããæååã bool() ã«æž¡ããŠãã bool('False') ã True ã«ãªã£ãŠããŸããŸããããã§ config parser 㯠getboolean() ãæäŸããŠããŸãããã®ã¡ãœããã¯å€§æåå°æåãåºå¥ããã 'yes'/'no'ã'on'/'off'ã'true'/'false'ã'1'/'0' ãçåœå€ãšããŠèªèããŸã [1]ãäŸãã°:
>>> topsecret.getboolean('ForwardX11')
False
>>> config['forge.example'].getboolean('ForwardX11')
True
>>> config.getboolean('forge.example', 'Compression')
True
config parser ã§ã¯ã getboolean() 以å€ã« getint() ãš getfloat() ã¡ãœãããæäŸãããŠããŸããç¬èªã®ã³ã³ããŒã¿ãŒã®ç»é²ãæäŸãããã¡ãœããã®ã«ã¹ã¿ãã€ãºãã§ããŸãã [1]
代æ¿å€Â¶
As with a dictionary, you can use a section's get() method to
provide fallback values:
>>> topsecret.get('Port')
'50022'
>>> topsecret.get('CompressionLevel')
'9'
>>> topsecret.get('Cipher')
>>> topsecret.get('Cipher', '3des-cbc')
'3des-cbc'
ããã©ã«ãå€ã¯ä»£æ¿å€ãããåªå
ãããããšã«æ³šæããŠãã ãããäŸãã°äžã®äŸã§ã¯ã'CompressionLevel' ããŒã¯ 'DEFAULT' ã»ã¯ã·ã§ã³ã«ããååšããŸããããã®å€ã 'topsecret.server.example' ããååŸããããšããå Žåã代æ¿å€ãæå®ããŠãåžžã«ããã©ã«ãå€ãè¿ããŸã:
>>> topsecret.get('CompressionLevel', '3')
'9'
One more thing to be aware of is that the parser-level get() method
provides a custom, more complex interface, maintained for backwards
compatibility. When using this method, a fallback value can be provided via
the fallback keyword-only argument:
>>> config.get('forge.example', 'monster',
... fallback='No such things as monsters')
'No such things as monsters'
åæ§ã® fallback åŒæ°ããgetint() ã getfloat() ãš getboolean() ã¡ãœããã§ã䜿ããŸããäŸãã°:
>>> 'BatchMode' in topsecret
False
>>> topsecret.getboolean('BatchMode', fallback=True)
True
>>> config['DEFAULT']['BatchMode'] = 'no'
>>> topsecret.getboolean('BatchMode', fallback=True)
False
ãµããŒãããINI ãã¡ã€ã«ã®æ§é ¶
A configuration file consists of sections, each led by a [section] header,
followed by key/value entries separated by a specific string (= or : by
default [1]). By default, section names are case sensitive but keys are not
[1]. Leading and trailing whitespace is removed from keys and values.
Values can be omitted if the parser is configured to allow it [1],
in which case the key/value delimiter may also be left
out. Values can also span multiple lines, as long as they are indented deeper
than the first line of the value. Depending on the parser's mode, blank lines
may be treated as parts of multiline values or ignored.
By default, a valid section name can be any string that does not contain '\n'.
To change this, see ConfigParser.SECTCRE.
The first section name may be omitted if the parser is configured to allow an
unnamed top level section with allow_unnamed_section=True. In this case,
the keys/values may be retrieved by UNNAMED_SECTION as in
config[UNNAMED_SECTION].
èšå®ãã¡ã€ã«ã«ã¯å
é ã«ç¹å®ã®æå (ããã©ã«ãã§ã¯ # ããã³ ; [1]) ãã€ããŠã³ã¡ã³ããã€ããããšãã§ããŸããã³ã¡ã³ãã¯ãä»ã®å
容ããªãè¡ã«çœ®ãããšãã§ããã€ã³ãã³ããããŠããŠãæ§ããŸããã[1]
äŸãã°:
[Simple Values]
key=value
spaces in keys=allowed
spaces in values=allowed as well
spaces around the delimiter = obviously
you can also use : to delimit keys from values
[All Values Are Strings]
values like this: 1000000
or this: 3.14159265359
are they treated as numbers? : no
integers, floats and booleans are held as: strings
can use the API to get converted values directly: true
[Multiline Values]
chorus: I'm a lumberjack, and I'm okay
I sleep all night and I work all day
[No Values]
key_without_value
empty string value here =
[You can use comments]
# like this
; or this
# By default only in an empty line.
# Inline comments can be harmful because they prevent users
# from using the delimiting characters as parts of values.
# That being said, this can be customized.
[Sections Can Be Indented]
can_values_be_as_well = True
does_that_mean_anything_special = False
purpose = formatting for readability
multiline_values = are
handled just fine as
long as they are indented
deeper than the first line
of a value
# Did I mention we can indent comments, too?
Unnamed Sections¶
The name of the first section (or unique) may be omitted and values
retrieved by the UNNAMED_SECTION attribute.
>>> config = """
... option = value
...
... [ Section 2 ]
... another = val
... """
>>> unnamed = configparser.ConfigParser(allow_unnamed_section=True)
>>> unnamed.read_string(config)
>>> unnamed.get(configparser.UNNAMED_SECTION, 'option')
'value'
å€ã®è£é¶
ã³ã¢æ©èœã«å ããŠã ConfigParser ã¯è£é(interpolation, å
æ¿ãšã)ããµããŒãããŸãããã㯠get() ã³ãŒã«ãå€ãè¿ãåã«ããã®å€ã«å¯ŸããŠååŠçãè¡ããããšãæå³ããŸãã
- class configparser.BasicInterpolation¶
ConfigParserã䜿çšããããã©ã«ãå®è£ ã§ããå€ã«ãåãã»ã¯ã·ã§ã³ãç¹å¥ãªããã©ã«ãã»ã¯ã·ã§ã³äž [1] ã®ä»ã®å€ãåç §ãããã©ãŒãããæååãå«ããããšãã§ããŸãã远å ã®ããã©ã«ãå€ãåæåæã«æäŸã§ããŸããäŸãã°:
[Paths] home_dir: /Users my_dir: %(home_dir)s/lumberjack my_pictures: %(my_dir)s/Pictures [Escape] # use a %% to escape the % sign (% is the only character that needs to be escaped): gain: 80%%
äžã®äŸã§ã¯ã interpolation ã«
BasicInterpolation()ãèšå®ããConfigParserã%(home_dir)sãhome_dirã®å€(ãã®ã±ãŒã¹ã§ã¯/Users)ãšããŠè§£æ±ºããŠããŸãããã®çµæ%(my_dir)sã¯/Users/lumberjackã«ãªããŸããå šãŠã®è£éã¯å¿ èŠã«å¿ããŠå®è¡ããããããèšå®ãã¡ã€ã«äžã§åç §ã®é£éããã€ããŒãç¹å®ã®é åºã§èšè¿°ããå¿ èŠã¯ãããŸãããinterpolationã«Noneãèšå®ããã°ãããŒãµãŒã¯åã«my_picturesã®å€ãšããŠ%(my_dir)s/Picturesãè¿ããmy_dirã®å€ãšããŠ%(home_dir)s/lumberjackãè¿ããŸãã
- class configparser.ExtendedInterpolation¶
zc.buildoutã§äœ¿çšããããããªãããé«åºŠãªææ³ãå®è£ ããè£éãã³ãã©ã®å¥ã®éžæè¢ã§ããæ¡åŒµãããè£éã¯ãä»ã®ã»ã¯ã·ã§ã³äžã®å€ã瀺ãã®ã«${section:option}ãšæžããŸããè£éã¯è€æ°ã®ã¬ãã«ã«åã¹ãŸããå©äŸ¿æ§ã®ããã«ãããsection:ã®éšåãçç¥ããããšãçŸåšã®ã»ã¯ã·ã§ã³ãããã©ã«ãå€ãšãªããŸã(ã¹ãã·ã£ã«ã»ã¯ã·ã§ã³äžã®ããã©ã«ãå€ã䜿çšããããšãã§ããŸã)ãããšãã°ãäžèšã® basic interpolation ã§æå®ããèšå®ã¯ãextended interpolation ã䜿ããšäžèšã®ããã«ãªããŸã:
[Paths] home_dir: /Users my_dir: ${home_dir}/lumberjack my_pictures: ${my_dir}/Pictures [Escape] # use a $$ to escape the $ sign ($ is the only character that needs to be escaped): cost: $$80
ä»ã®ã»ã¯ã·ã§ã³ããå€ãæã£ãŠããããšãã§ããŸã:
[Common] home_dir: /Users library_dir: /Library system_dir: /System macports_dir: /opt/local [Frameworks] Python: 3.2 path: ${Common:system_dir}/Library/Frameworks/ [Arthur] nickname: Two Sheds last_name: Jackson my_dir: ${Common:home_dir}/twosheds my_pictures: ${my_dir}/Pictures python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
ãããåãããã³ã«ã¢ã¯ã»ã¹Â¶
Added in version 3.2.
Mapping protocol access is a generic name for functionality that enables using
custom objects as if they were dictionaries. In case of configparser,
the mapping interface implementation is using the
parser['section']['option'] notation.
ãšãã«ãparser['section'] ã¯ããŒãµãŒå
ã®ãã®ã»ã¯ã·ã§ã³ã®ããŒã¿ãžã®ãããã·ãè¿ããŸããã€ãŸããå€ã¯ã³ããŒãããã®ã§ã¯ãªãå¿
èŠã«å¿ããŠãªãªãžãã«ã®ããŒãµãŒããåãããŸããããã«éèŠãªããšã«ãã»ã¯ã·ã§ã³ã®ãããã·ã®å€ã倿Žããããšããªãªãžãã«ã®ããŒãµãŒäžã®å€ãå®éã«å€æŽãããŸãã
configparser objects behave as close to actual dictionaries as possible.
The mapping interface is complete and adheres to the
MutableMapping ABC.
However, there are a few differences that should be taken into account:
ããã©ã«ãã§ã¯ãã»ã¯ã·ã§ã³å ã®å šãŠã®ããŒã¯å€§æåå°æåã®åºå¥ãªãã¢ã¯ã»ã¹ã§ããŸã [1]ãäŸãã°ã
for option in parser["section"]ã¯optionxformããããªãã·ã§ã³ããŒåã®ã¿ã yield ããŸããã€ãŸãå°æåã®ããŒãããã©ã«ãã§ããåæã«ãããŒ'a'ãå«ãã»ã¯ã·ã§ã³ã«ãããŠãã©ã¡ãã®åŒãTrueãè¿ããŸã:"a" in parser["section"] "A" in parser["section"]
å šãŠã®ã»ã¯ã·ã§ã³ã¯
DEFAULTSECTå€ãæã¡ãããªãã¡ã»ã¯ã·ã§ã³ã§.clear()ããŠãã»ã¯ã·ã§ã³ã¯èŠãç®äžç©ºã«ãªããŸãããããã¯ãããã©ã«ãå€ã¯ (æè¡çã«ã¯ããã«ãªãã®ã§) ã»ã¯ã·ã§ã³ããåé€ã§ããªãããã§ããããã©ã«ãå€ãäžæžããããå Žåããããåé€ããããšããã©ã«ãå€ãåã³èŠããããã«ãªããŸããããã©ã«ãå€ãåé€ããããšãããšKeyErrorãçºçããŸããDEFAULTSECTã¯ããŒãµãŒããåãé€ããŸãã:åé€ããããšãããš
ValueErrorãçºçããŸããparser.clear()ã¯ããããã®ãŸãŸæ®ããparser.popitem()ããããè¿ãããšã¯ãããŸããã
parser.get(section, option, **kwargs)- 第äºåŒæ°ã¯ä»£æ¿å€ã§ã¯ ãããŸããããã ããã»ã¯ã·ã§ã³ããšã®get()ã¡ãœããã¯ãããåãããã³ã«ãšæ§åŒã® configparser API ã®äž¡æ¹ã«äºæã§ããparser.items()ã¯ãããåãããã³ã«ãšäºæã§ã (DEFAULTSECT ãå«ã section_name, section_proxy 察ã®ãªã¹ããè¿ããŸã)ããã ãããã®ã¡ãœããã¯parser.items(section, raw, vars)ã®ããã«ããŠåŒæ°ãäžããããšã§ãåŒã³åºããŸããåŸè ã®åŒã³åºãã¯æå®ãããsectionã® option, value 察ã®ãªã¹ããã(raw=Trueãäžããããªãéã) å šãŠã®è£éãå±éããŠè¿ããŸãã
ãããåãããã³ã«ã¯ãæ¢åã®ã¬ã¬ã·ãŒãª API ã®äžã«å®è£ ãããŠããã®ã§ããªãªãžãã«ã®ã€ã³ã¿ãŒãã§ãŒã¹ãäžæžãããæŽŸçã¯ã©ã¹ããŸãã¯æåŸ ã©ããã«ã¯ããããŸãã
ããŒãµãŒã®æ¯ãèããã«ã¹ã¿ãã€ãºãã¶
There are nearly as many INI format variants as there are applications using it.
configparser goes a long way to provide support for the largest sensible
set of INI styles available. The default functionality is mainly dictated by
historical background and it's very likely that you will want to customize some
of the features.
The most common way to change the way a specific config parser works is to use
the __init__() options:
defaults, ããã©ã«ãå€:
Noneãã®ãªãã·ã§ã³ã¯æåã«
DEFAULTã»ã¯ã·ã§ã³ã«å ããããããŒ-å€ã®å¯Ÿã®èŸæžãåãä»ããŸããHint: if you want to specify default values for a specific section, use
read_dict()before you read the actual file.dict_type, ããã©ã«ãå€:
dictãã®ãªãã·ã§ã³ã¯ãããåãããã³ã«ã®æ¯ãèãæ¹ãæžã蟌ãŸããèšå®ãã¡ã€ã«ã®èŠãç®ã«å€§ãã圱é¿ããŸããæšæºã®èŸæžã§ã¯ãå šãŠã®ã»ã¯ã·ã§ã³ã¯ããŒãµãŒã«å ããããé ã«äžŠã³ãŸããåãããšãã»ã¯ã·ã§ã³å ã®ãªãã·ã§ã³ã«ãèšããŸãã
ã»ã¯ã·ã§ã³ãšãªãã·ã§ã³ãã©ã€ãããã¯æã«ãœãŒããããããªã©ã«ãå¥ã®èŸæžåã䜿ããŸãã
泚æ: äžåºŠã®æäœã§ããŒ-å€ã®å¯Ÿãè€æ°è¿œå ããæ¹æ³ããããŸãããã®ãããªæäœã«æ®éã®èŸæžã䜿ããšãããŒã®äžŠã³ã¯æ¿å ¥é ã«ãªããŸããäŸãã°:
>>> parser = configparser.ConfigParser() >>> parser.read_dict({'section1': {'key1': 'value1', ... 'key2': 'value2', ... 'key3': 'value3'}, ... 'section2': {'keyA': 'valueA', ... 'keyB': 'valueB', ... 'keyC': 'valueC'}, ... 'section3': {'foo': 'x', ... 'bar': 'y', ... 'baz': 'z'} ... }) >>> parser.sections() ['section1', 'section2', 'section3'] >>> [option for option in parser['section3']] ['foo', 'bar', 'baz']
allow_no_value, ããã©ã«ãå€:
FalseSome configuration files are known to include settings without values, but which otherwise conform to the syntax supported by
configparser. The allow_no_value parameter to the constructor can be used to indicate that such values should be accepted:>>> import configparser >>> sample_config = """ ... [mysqld] ... user = mysql ... pid-file = /var/run/mysqld/mysqld.pid ... skip-external-locking ... old_passwords = 1 ... skip-bdb ... # we don't need ACID today ... skip-innodb ... """ >>> config = configparser.ConfigParser(allow_no_value=True) >>> config.read_string(sample_config) >>> # Settings with values are treated as before: >>> config["mysqld"]["user"] 'mysql' >>> # Settings without values provide None: >>> config["mysqld"]["skip-bdb"] >>> # Settings which aren't specified still raise an error: >>> config["mysqld"]["does-not-exist"] Traceback (most recent call last): ... KeyError: 'does-not-exist'
delimiters, ããã©ã«ãå€:
('=', ':')ããªãã¿ã¯ã»ã¯ã·ã§ã³å ã§ããŒãå€ããåºåãéšåæååã§ããè¡äžã§æåã«çŸããåºåãéšåæååãããªãã¿ãšèŠãªãããŸããã€ãŸãå€ã«ã¯ããªãã¿ãå«ããããšãã§ããŸã (ããŒã«ã¯å«ããããšãã§ããŸãã)ã
ConfigParser.write()ã® space_around_delimiters åŒæ°ãåç §ããŠãã ãããcomment_prefixes, ããã©ã«ãå€:
('#', ';')inline_comment_prefixes, ããã©ã«ãå€:
Noneã³ã¡ã³ãæ¥é èŸã¯èšå®ãã¡ã€ã«äžã§æå¹ãªã³ã¡ã³ãã®éå§ã瀺ãæååã§ããcomment_prefixes ã¯ä»ã®å 容ããªãè¡ (ã€ã³ãã³ãã¯èªç±) ã«ã®ã¿äœ¿çšã§ããinline_comment_prefixes ã¯ä»»æã®æå¹ãªå€ (äŸãã°ãã»ã¯ã·ã§ã³åããªãã·ã§ã³ã空è¡ãå¯èœ) ã®åŸã«äœ¿ããŸããããã©ã«ãã§ã¯ã€ã³ã©ã€ã³ã³ã¡ã³ãã¯ç¡å¹åãããŠããŠã
'#'ãš';'ãè¡å šäœã®ã³ã¡ã³ãã«äœ¿çšããŸããããŒãžã§ã³ 3.2 ã§å€æŽ: In previous versions of
configparserbehaviour matchedcomment_prefixes=('#',';')andinline_comment_prefixes=(';',).èšå®ããŒãµãŒã¯ã³ã¡ã³ãæ¥é èŸã®ãšã¹ã±ãŒãããµããŒãããªãã®ã§ãinline_comment_prefixes ã¯ãŠãŒã¶ãŒãã³ã¡ã³ãæ¥é èŸãšããŠäœ¿ãããæåãå«ããªãã·ã§ã³å€ãæå®ããã®ã劚ããå¯èœæ§ããããŸããçãããå Žåã«ã¯ãinline_comment_prefixes ãèšå®ããªãããã«ããŠãã ãããã©ã®ãããªç¶æ³ã§ããè€æ°è¡ã«ãããå€ã§ãè¡ã®å é ã«ã³ã¡ã³ãæ¥é èŸæåãä¿åããå¯äžã®æ¹æ³ã¯ã次ã®äŸã®ããã«æ¥é èŸãè£éããããšã§ã:
>>> from configparser import ConfigParser, ExtendedInterpolation >>> parser = ConfigParser(interpolation=ExtendedInterpolation()) >>> # the default BasicInterpolation could be used as well >>> parser.read_string(""" ... [DEFAULT] ... hash = # ... ... [hashes] ... shebang = ... ${hash}!/usr/bin/env python ... ${hash} -*- coding: utf-8 -*- ... ... extensions = ... enabled_extension ... another_extension ... #disabled_by_comment ... yet_another_extension ... ... interpolation not necessary = if # is not at line start ... even in multiline values = line #1 ... line #2 ... line #3 ... """) >>> print(parser['hashes']['shebang']) #!/usr/bin/env python # -*- coding: utf-8 -*- >>> print(parser['hashes']['extensions']) enabled_extension another_extension yet_another_extension >>> print(parser['hashes']['interpolation not necessary']) if # is not at line start >>> print(parser['hashes']['even in multiline values']) line #1 line #2 line #3
strict, ããã©ã«ãå€:
TrueWhen set to
True, the parser will not allow for any section or option duplicates while reading from a single source (usingread_file(),read_string()orread_dict()). It is recommended to use strict parsers in new applications.ããŒãžã§ã³ 3.2 ã§å€æŽ: In previous versions of
configparserbehaviour matchedstrict=False.empty_lines_in_values, ããã©ã«ãå€:
Trueèšå®ããŒãµãŒã§ã¯ãããŒããããã®å€ãæ·±ãã€ã³ãã³ãããããããè€æ°è¡ã«ãŸãããå€ã䜿ããŸããããã©ã«ãã®ããŒãµãŒã¯ããã«ãã®å€ã®éã«ç©ºè¡ã眮ããŸããåæã«ãããŒã¯èªã¿ãããããããä»»æã«ã€ã³ãã³ãã§ããŸããçµæãšããŠãèšå®ãã¡ã€ã«ã倧ããè€éã«ãªã£ããšãããŠãŒã¶ãŒããã¡ã€ã«æ§é ãèŠå€±ããããã§ãããã®äŸãã芧ãã ãã:
[Section] key = multiline value with a gotcha this = is still a part of the multiline value of 'key'
ããã¯ç¹ã«ããããŒã·ã§ãã«ãã©ã³ãã䜿ã£ãŠãã¡ã€ã«ãç·šéããŠãããŠãŒã¶ãŒã«ãšã£ãŠåé¡ã«ãªãããšããããŸããã ãããã¢ããªã±ãŒã·ã§ã³ã®å€ã«ç©ºè¡ãå¿ èŠãªããªãã空è¡ãèªããªãã¹ãã§ããããã«ãã£ãŠç©ºè¡ã§å¿ ãããŒãåãããŸããäžã®äŸã§ã¯ã2 ã€ã®ããŒã
keyããã³thisãäœãããŸããdefault_section, ããã©ã«ãå€:
configparser.DEFAULTSECT(ããªãã¡:"DEFAULT")ä»ã®ã»ã¯ã·ã§ã³ã®ããã©ã«ãå€ãè£éç®çã§ã®ç¹å¥ãªã»ã¯ã·ã§ã³ãèªããæ £è¡ã¯ãã®ã©ã€ãã©ãªã®æç¢ºãªã³ã³ã»ããã®äžã€ã§ããŠãŒã¶ãŒã¯è€éã§å®£èšçãªèšå®ãäœæã§ããŸãããã®ã»ã¯ã·ã§ã³ã¯éåžž
"DEFAULT"ãšåŒã°ããŸãããä»»æã®æå¹ãªã»ã¯ã·ã§ã³åãæãããã«ã«ã¹ã¿ãã€ãºã§ããŸããå žåçãªå€ã«ã¯"general"ã"common"ããããŸããäžããããååã¯ãœãŒã¹ãèªã¿èŸŒãéã«ããã©ã«ãã»ã¯ã·ã§ã³ãèªèããã®ã«äœ¿ãããèšå®ããã¡ã€ã«ã«æžãæ»ããšãã«ã䜿ãããŸããçŸåšã®å€ã¯parser_instance.default_section屿§ããåãåºãããšãã§ããå®è¡æ (ããªãã¡ãã¡ã€ã«ãå¥ã®ãã©ãŒãããã«å€æãããšã) ã«å€æŽããããšãã§ããŸããinterpolation, ããã©ã«ãå€:
configparser.BasicInterpolationè£éã®æ¯ãèãã¯ã interpolation åŒæ°ãéããŠã«ã¹ã¿ã ãã³ãã©ãäžããããšã§ã«ã¹ã¿ãã€ãºã§ããŸãã
NoneåŒæ°ã䜿ããšè£éãå®å šã«ç¡å¹ã«ã§ããŸããExtendedInterpolation()ã¯ãzc.buildoutã«åœ±é¿ãåããããé«åºŠãªè£éãæäŸããŸãããã®è©±é¡ã« ç¹åããããã¥ã¡ã³ãã®ã»ã¯ã·ã§ã³ ãã芧ãã ãããRawConfigParserã®ããã©ã«ãå€ã¯Noneã§ããconverters, ããã©ã«ãå€: æªèšå®
Config parsers provide option value getters that perform type conversion. By default
getint(),getfloat(), andgetboolean()are implemented. Should other getters be desirable, users may define them in a subclass or pass a dictionary where each key is a name of the converter and each value is a callable implementing said conversion. For instance, passing{'decimal': decimal.Decimal}would addgetdecimal()on both the parser object and all section proxies. In other words, it will be possible to write bothparser_instance.getdecimal('section', 'key', fallback=0)andparser_instance['section'].getdecimal('key', 0).ã³ã³ããŒã¿ãŒãããŒãµãŒã®ç¶æ ã«ã¢ã¯ã»ã¹ããå¿ èŠãããå Žåãèšå®ããŒãµãŒãµãã¯ã©ã¹ã§ã¡ãœãããšããŠå®è£ ããããšãã§ããŸãããã®ã¡ãœããã®ååã
getããå§ãŸãå Žåããã¹ãŠã®ã»ã¯ã·ã§ã³ãããã·ã§ãèŸæžãšäºææ§ã®ãã圢åŒã§å©çšã§ããŸã (äžèšã®getdecimal()ã®äŸãåç §)ã
ãããã®ããŒãµãŒåŒæ°ã®ããã©ã«ãå€ãäžæžãããã°ãããã«é²ãã ã«ã¹ã¿ãã€ãºãã§ããŸããããã©ã«ãã¯ã¯ã©ã¹ã§å®çŸ©ãããŠããã®ã§ã掟çã¯ã©ã¹ã屿§ã®ä»£å ¥ã§äžæžãã§ããŸãã
- ConfigParser.BOOLEAN_STATES¶
ããã©ã«ãã§ã¯ã
getboolean()ã䜿ãããšã§ãèšå®ããŒãµãŒã¯ä»¥äžã®å€ãTrueãšèŠãªããŸã:'1','yes','true','on'ã以äžã®å€ãFalseãšèŠãªããŸã:'0','no','false','off'ãæååãšå¯Ÿå¿ããããŒã«å€ã®ã«ã¹ã¿ã èŸæžãæå®ããããšã§ãããäžæžãã§ããŸããããšãã°:>>> custom = configparser.ConfigParser() >>> custom['section1'] = {'funky': 'nope'} >>> custom['section1'].getboolean('funky') Traceback (most recent call last): ... ValueError: Not a boolean: nope >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False} >>> custom['section1'].getboolean('funky') False
ã»ãã®å žåçãªããŒã«å€ãã¢ã«ã¯
accept/rejectãenabled/disabledãªã©ããããŸãã
- ConfigParser.optionxform(option)
ãã®ã¡ãœããã¯èªã¿èŸŒã¿ãååŸãèšå®æäœã®ãã³ã«ãªãã·ã§ã³åã倿ããŸããããã©ã«ãã§ã¯ååãå°æåã«å€æããŸããåŸã£ãŠèšå®ãã¡ã€ã«ãæžã蟌ãŸãããšãããã¹ãŠã®ããŒã¯å°æåã«ãªããŸããããããµãããããªããã°ããã®ã¡ãœãããäžæžãããŠãã ãããäŸãã°:
>>> config = """ ... [Section1] ... Key = Value ... ... [Section2] ... AnotherKey = Value ... """ >>> typical = configparser.ConfigParser() >>> typical.read_string(config) >>> list(typical['Section1'].keys()) ['key'] >>> list(typical['Section2'].keys()) ['anotherkey'] >>> custom = configparser.RawConfigParser() >>> custom.optionxform = lambda option: option >>> custom.read_string(config) >>> list(custom['Section1'].keys()) ['Key'] >>> list(custom['Section2'].keys()) ['AnotherKey']
泚é
The optionxform function transforms option names to a canonical form. This should be an idempotent function: if the name is already in canonical form, it should be returned unchanged.
- ConfigParser.SECTCRE¶
ã»ã¯ã·ã§ã³ããããè§£æããã®ã«äœ¿ããããã³ã³ãã€ã«ãããæ£èŠè¡šçŸã§ããããã©ã«ãã§ã¯
[section]ã"section"ãšããååã«ãããããŸãã空çœã¯ã»ã¯ã·ã§ã³åã®äžéšãšèŠãªãããã®ã§ã[ larch ]ã¯" larch "ãšããåã®ã»ã¯ã·ã§ã³ãšããŠèªã¿èŸŒãŸããŸããããããµãããããªãå Žåããã®ã¡ãœãããäžæžãããŠãã ãããäŸãã°:>>> import re >>> config = """ ... [Section 1] ... option = value ... ... [ Section 2 ] ... another = val ... """ >>> typical = configparser.ConfigParser() >>> typical.read_string(config) >>> typical.sections() ['Section 1', ' Section 2 '] >>> custom = configparser.ConfigParser() >>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]") >>> custom.read_string(config) >>> custom.sections() ['Section 1', 'Section 2']
泚é
ConfigParser ãªããžã§ã¯ãã¯ãªãã·ã§ã³è¡ã®èªèã«
OPTCRE屿§ã䜿ããŸããããããäžæžãããããšã¯æšå¥šãããŸãããäžæžããããšã³ã³ã¹ãã©ã¯ã¿ãªãã·ã§ã³ allow_no_value ããã³ delimiters ã«å¹²æžããŸãã
ã¬ã¬ã·ãŒãª API ã®äŸÂ¶
Mainly because of backwards compatibility concerns, configparser
provides also a legacy API with explicit get/set methods. While there
are valid use cases for the methods outlined below, mapping protocol access is
preferred for new projects. The legacy API is at times more advanced,
low-level and downright counterintuitive.
èšå®ãã¡ã€ã«ãæžãåºãäŸ:
import configparser
config = configparser.RawConfigParser()
# Please note that using RawConfigParser's set functions, you can assign
# non-string values to keys internally, but will receive an error when
# attempting to write to a file or when you get it in non-raw mode. Setting
# values using the mapping protocol or ConfigParser's set() does not allow
# such assignments to take place.
config.add_section('Section1')
config.set('Section1', 'an_int', '15')
config.set('Section1', 'a_bool', 'true')
config.set('Section1', 'a_float', '3.1415')
config.set('Section1', 'baz', 'fun')
config.set('Section1', 'bar', 'Python')
config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
# Writing our configuration file to 'example.cfg'
with open('example.cfg', 'w') as configfile:
config.write(configfile)
èšå®ãã¡ã€ã«ãèªã¿èŸŒãäŸ:
import configparser
config = configparser.RawConfigParser()
config.read('example.cfg')
# getfloat() raises an exception if the value is not a float
# getint() and getboolean() also do this for their respective types
a_float = config.getfloat('Section1', 'a_float')
an_int = config.getint('Section1', 'an_int')
print(a_float + an_int)
# Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
# This is because we are using a RawConfigParser().
if config.getboolean('Section1', 'a_bool'):
print(config.get('Section1', 'foo'))
è£éããã«ã¯ã ConfigParser ã䜿ã£ãŠãã ãã:
import configparser
cfg = configparser.ConfigParser()
cfg.read('example.cfg')
# Set the optional *raw* argument of get() to True if you wish to disable
# interpolation in a single get operation.
print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!"
print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!"
# The optional *vars* argument is a dict with members that will take
# precedence in interpolation.
print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',
'baz': 'evil'}))
# The optional *fallback* argument can be used to provide a fallback value
print(cfg.get('Section1', 'foo'))
# -> "Python is fun!"
print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
# -> "Python is fun!"
print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
# -> "No such things as monsters."
# A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
# but we can also use:
print(cfg.get('Section1', 'monster', fallback=None))
# -> None
ã©ã¡ãã®åã® ConfigParsers ã§ãããã©ã«ãå€ãå©çšã§ããŸãã䜿ãããŠãããªãã·ã§ã³ãã©ãã«ãå®çŸ©ãããŠããªããã°ããã®ããã©ã«ãå€ãè£éã«äœ¿ãããŸãã
import configparser
# New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})
config.read('example.cfg')
print(config.get('Section1', 'foo')) # -> "Python is fun!"
config.remove_option('Section1', 'bar')
config.remove_option('Section1', 'baz')
print(config.get('Section1', 'foo')) # -> "Life is hard!"
ConfigParser ãªããžã§ã¯ã¶
- class configparser.ConfigParser(defaults=None, dict_type=dict, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation(), converters={}, allow_unnamed_section=False)¶
äž»èŠãªèšå®ããŒãµãŒã§ããdefaults ãäžããããã°ããã®èŸæžã®æã€åæå€ã§åæåãããŸããdict_type ãäžããããã°ããããã»ã¯ã·ã§ã³ã®äžèЧãã»ã¯ã·ã§ã³äžã®ãªãã·ã§ã³ãããã³ããã©ã«ãå€ã®èŸæžãªããžã§ã¯ããäœæããã®ã«äœ¿ãããŸãã
delimiters ãäžããããå ŽåãããŒãšå€ãåå²ããéšåæååã®çµã¿åãããšããŠäœ¿ãããŸããcomment_prefixes ãäžããããå Žåãä»ã®å 容ããªãè¡ã®ã³ã¡ã³ãã«æ¥é ããéšåæååã®çµã¿åãããšããŠäœ¿ãããŸããã³ã¡ã³ãã¯ã€ã³ãã³ãã§ããŸããinline_comment_prefixes ãäžããããå Žåãé空è¡ã®ã³ã¡ã³ãã«æ¥é ããéšåæååãšããŠã®çµã¿åãããšããŠäœ¿ãããŸãã
strict ã
True(ããã©ã«ã) ã§ããã°ãããŒãµãŒã¯åäžã®ãœãŒã¹ (ãã¡ã€ã«ãæååãèŸæž) äžã«ã»ã¯ã·ã§ã³ããªãã·ã§ã³ã®éè€ãèªãããDuplicateSectionErrorãDuplicateOptionErrorãéåºããŸãã empty_lines_in_values ãFalse(ããã©ã«ã:True) ãªãã空è¡ã¯ãããããªãã·ã§ã³ã®çµããã瀺ããŸãã allow_no_value ãTrue(ããã©ã«ã:False) ãªããå€ã®ãªããªãã·ã§ã³ãåãä»ããããŸãããã®ãªãã·ã§ã³ã®å€ã¯NoneãšãªããåŸç«¯ã®ããªãã¿ãé€ããŠã·ãªã¢ã«åãããŸããWhen 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 thedefault_sectioninstance 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 åŒæ°ãéããŠã«ã¹ã¿ã ãã³ãã©ãäžããããšã§ã«ã¹ã¿ãã€ãºã§ããŸãã
NoneåŒæ°ã䜿ããšè£éãå®å šã«ç¡å¹ã«ã§ããŸããExtendedInterpolation()ã¯ãzc.buildoutã«åœ±é¿ãåããããé«åºŠãªè£éãæäŸããŸãããã®ä»¶ã« ç¹åããããã¥ã¡ã³ãã®ã»ã¯ã·ã§ã³ ãåç §ããŠãã ãããè£éã«äœ¿ããããã¹ãŠã®ãªãã·ã§ã³åã¯ãä»ã®ãªãã·ã§ã³ååç §ãšåæ§ã«ã
optionxform()ã¡ãœãããéããŠæž¡ãããŸããäŸãã°ãoptionxform()ã®ããã©ã«ãã®å®è£ ã䜿ããšãå€foo %(bar)sãšfoo %(BAR)sã¯çãããªããŸããWhen 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.When 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 anoverride.inifile, which will override any conflicting keys from theexample.inifile.[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 ã¯
collections.OrderedDictã§ããããŒãžã§ã³ 3.2 ã§å€æŽ: allow_no_value, delimiters, comment_prefixes, strict, empty_lines_in_values, default_section ããã³ interpolation ã远å ãããŸããã
ããŒãžã§ã³ 3.5 ã§å€æŽ: 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 ã§å€æŽ: The default dict_type is
dict, since it now preserves insertion order.ããŒãžã§ã³ 3.13 ã§å€æŽ: Raise a
MultilineContinuationErrorwhen allow_no_value isTrue, and a key without a value is continued with an indented line.ããŒãžã§ã³ 3.13 ã§å€æŽ: The allow_unnamed_section argument was added.
- defaults()¶
ã€ã³ã¹ã¿ã³ã¹å šäœã§äœ¿ãããããã©ã«ãå€ã®èŸæžãè¿ããŸãã
- sections()¶
å©çšã§ããã»ã¯ã·ã§ã³ã®ãªã¹ããè¿ããŸããdefault section ã¯ãªã¹ãã«å«ãŸããŸããã
- add_section(section)¶
section ãšããåã®ã»ã¯ã·ã§ã³ãã€ã³ã¹ã¿ã³ã¹ã«è¿œå ããŸããäžããããååã®ã»ã¯ã·ã§ã³åããã§ã«ååšãããã
DuplicateSectionErrorãéåºãããŸãã default section åãæž¡ãããããValueErrorãéåºãããŸããã»ã¯ã·ã§ã³ã®ååã¯æååã§ãªããã°ãªããŸãããããã§ãªããã°ãTypeErrorãéåºãããŸããããŒãžã§ã³ 3.2 ã§å€æŽ: æååã§ãªãã»ã¯ã·ã§ã³åã¯
TypeErrorãéåºããŸãã
- has_section(section)¶
æåããã section ãèšå®äžã«ååšãããã瀺ããŸããdefault section ã¯èªèãããŸããã
- options(section)¶
æå®ããã section äžã§å©çšã§ãããªãã·ã§ã³ã®ãªã¹ããè¿ããŸãã
- has_option(section, option)¶
äžãããã section ãååšããäžãããã option ãå«ãå Žåã
Trueãè¿ããŸãããã以å€ã®å Žåã«ã¯ãFalseãè¿ããŸããæå®ããã section ãNoneãŸãã¯ç©ºæååã®å Žåã DEFAULT ãä»®å®ãããŸãã
- read(filenames, encoding=None)¶
ãã¡ã€ã«åã® iterable ãèªã¿èŸŒãã§ããŒã¹ããããšè©Šã¿ãŸããæ£åžžã«ããŒã¹ã§ãããã¡ã€ã«åã®ãªã¹ããè¿ããŸãã
ãã filenames ãæååã
bytesãªããžã§ã¯ãã path-like object ãªãããã®åŒæ°ã¯1ã€ã®ãã¡ã€ã«åãšããŠæ±ãããŸãã filenames äžã«éããªããã¡ã€ã«ãããå Žåããã®ãã¡ã€ã«ã¯ç¡èŠãããŸãããã®æåã¯ãèšå®ãã¡ã€ã«ã眮ãããå¯èœæ§ã®ããå Žæ(äŸãã°ã ã«ã¬ã³ããã£ã¬ã¯ããªãããŒã ãã£ã¬ã¯ããªãã·ã¹ãã å šäœã®èšå®ãè¡ããã£ã¬ã¯ããª)ã®ã€ãã©ãã«ãæå®ããŠãã€ãã©ãã«ã®äžã§ååšããå šãŠã®èšå®ãã¡ã€ã«ãèªãããšãæ³å®ããŠèšèšãããŠããŸããã©ã®èšå®ãã¡ã€ã«ãååšããªãã£ãå Žåã
ConfigParserã®ã€ã³ã¹ã¿ã³ã¹ã¯ 空ã®ããŒã¿ã»ãããæã¡ãŸããåæå€ã®èšå®ãã¡ã€ã«ãå ã«èªã¿èŸŒãã§ããå¿ èŠãããã¢ããªã±ãŒã·ã§ã³ã§ã¯ã ãªãã·ã§ã³ã®ãã¡ã€ã«ãèªã¿èŸŒãããã«read()ãåŒã¶åã« ããŸãread_file()ãçšããŠå¿ èŠãªãã¡ã€ã«ãèªã¿èŸŒãã§ãã ãã: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 ã§å€æŽ: Added the encoding parameter. Previously, all files were read using the default encoding for
open().ããŒãžã§ã³ 3.6.1 ã§å€æŽ: filenames åŒæ°ã path-like object ãåãå ¥ããããã«ãªããŸããã
ããŒãžã§ã³ 3.7 ã§å€æŽ: filenames åŒæ°ã
bytesãªããžã§ã¯ããåãå ¥ããããã«ãªããŸããã
- read_file(f, source=None)¶
èšå®ããŒã¿ã f ããèªã¿èŸŒãã§è§£æããŸããf 㯠Unicode æååã yield ããã€ãã©ãã« (äŸãã°ããã¹ãã¢ãŒãã§éããããã¡ã€ã«) ã§ãã
Optional argument source specifies the name of the file being read. If not given and f has a
nameattribute, that is used for source; the default is'<???>'.Added in version 3.2:
readfp()ã眮ãæããŸãã
- read_string(string, source='<string>')¶
èšå®ããŒã¿ãæååããè§£æããŸãã
ãªãã·ã§ã³ã®åŒæ° source ã¯ã³ã³ããã¹ãã«ãããæž¡ãããæååã®ååãæå®ããŸããäžããããªããã°ã
'<string>'ã䜿ãããŸããããã¯äžè¬ã«ãã¡ã€ã«ã·ã¹ãã ãã¹ã URL ã«ããŸããAdded in version 3.2.
- read_dict(dictionary, source='<dict>')¶
èŸæžçãª
items()ã¡ãœãããæäŸããä»»æã®ãªããžã§ã¯ãããèšå®ãèªã¿èŸŒã¿ãŸããããŒã¯ã»ã¯ã·ã§ã³åã§ãå€ã¯ãã®ã»ã¯ã·ã§ã³ã«çŸããããŒãšå€ããã€èŸæžã§ãã䜿ãããèŸæžåãé åºãä¿åãããªããã»ã¯ã·ã§ã³ããã³ãã®ããŒã¯é ã«å ããããŸããå€ã¯èªåã§æååã«å€æãããŸãããªãã·ã§ã³ã®åŒæ° source ã¯ã³ã³ããã¹ãã«ãããæž¡ãããèŸæžã®ååãæå®ããŸããäžããããªããã°ã
<dict>ã䜿ãããŸãããã®ã¡ãœããã䜿ã£ãŠããŒãµãŒéã§ç¶æ ãã³ããŒã§ããŸãã
Added in version 3.2.
- get(section, option, *, raw=False, vars=None[, fallback])¶
æåããã section ã® option ã®å€ãååŸããŸããvars ãæäŸããããªããããã¯èŸæžã§ãªããã°ãªããã(äžãããããªã) vars, section, DEFAULTSECT å ãããã®é ã§ option ãæ¢çŽ¢ãããŸããfallback ã®å€ãšããŠ
NoneãäžããããŸããraw ãçã§ãªãæã«ã¯ãå šãŠã®
'%'眮æã¯å±éãããŠããè¿ãããŸãã眮æåŸã®å€ã¯ãªãã·ã§ã³ãšåãé åºã§æ¢ãããŸããããŒãžã§ã³ 3.2 ã§å€æŽ: åŒæ° raw, vars ããã³ fallback ã¯ã(ç¹ã«ãããã³ã°ãããã³ã«ã䜿çšãããšãã«) ãŠãŒã¶ãŒã第 3 åŒæ°ã fallback ãã©ãŒã«ããã¯ãšããŠäœ¿ãããšããªãããã«ãããŒã¯ãŒãå°çšãšãªããŸããã
- getint(section, option, *, raw=False, vars=None[, fallback])¶
æå®ããã section äžã® option ãæŽæ°ã«å匷å¶ããè£å©ã¡ãœããã§ãã raw, vars ããã³ fallback ã®èª¬æã¯
get()ãåç §ããŠãã ããã
- getfloat(section, option, *, raw=False, vars=None[, fallback])¶
A convenience method which coerces the option in the specified section to a floating-point number. See
get()for explanation of raw, vars and fallback.
- getboolean(section, option, *, raw=False, vars=None[, fallback])¶
æå®ããã section äžã® option ãããŒã«å€ã«å匷å¶ããè£å©ã¡ãœããã§ãããªãããã®ãªãã·ã§ã³ã§åãä»ããããå€ã¯ãã®ã¡ãœããã
Trueãè¿ã'1','yes','true', ããã³'on',ãšããã®ã¡ãœãããFalseãè¿ã'0','no','false', and'off'ã§ãããã®ä»ã®ãããªãå€ãValueErrorãéåºããŸãã raw, vars ããã³ fallback ã®èª¬æã¯get()ãåç §ããŠãã ããã
- items(raw=False, vars=None)¶
- items(section, raw=False, vars=None)
section ãäžããããªããã°ãDEFAULTSECT ãå«ãã section_name, section_proxy ã®å¯Ÿã®ãªã¹ããè¿ããŸãã
äžããããã°ãäžãããã section äžã®ãªãã·ã§ã³ã® name, value ã®å¯Ÿã®ãªã¹ããè¿ããŸãããªãã·ã§ã³ã®åŒæ°ã¯
get()ã¡ãœããã«äžãããã®ãšåãæå³ãæã¡ãŸããããŒãžã§ã³ 3.8 ã§å€æŽ: vars ã«çŸããé ç®ã¯çµæã«è¡šããªããªããŸããã以åã®æåã¯ãå®éã®ããŒãµãŒãªãã·ã§ã³ãè£éã®ããã«äžãããã倿°ãšæ··åããŠããŸããã
- set(section, option, value)¶
äžããããã»ã¯ã·ã§ã³ãååšããã°ãäžãããããªãã·ã§ã³ãæå®ãããå€ã«èšå®ããŸããããã§ãªããã°
NoSectionErrorãéåºããŸãã option ããã³ value ã¯æååã§ãªããã°ãªããŸãããããã§ãªããã°TypeErrorãéåºãããŸãã
- write(fileobject, space_around_delimiters=True)¶
èšå®ã®è¡šçŸãæå®ããã file object ã«æžã蟌ã¿ãŸãã fileobject 㯠(æååãåãä»ãã) ããã¹ãã¢ãŒãã§éãããŠããªããã°ãªããŸããããã®è¡šçŸã¯åŸã§
read()ãåŒã³åºãããšã§ããŒã¹ã§ããŸãã space_around_delimiters ãçãªããããŒãšå€ã®éã®ããªãã¿ã¯ã¹ããŒã¹ã§å²ãŸããŸããããŒãžã§ã³ 3.14 ã§å€æŽ: Raises InvalidWriteError if this would write a representation which cannot be accurately parsed by a future
read()call from this parser.
泚é
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)¶
æå®ããã option ãæå®ããã section ããåé€ããŸããã»ã¯ã·ã§ã³ãååšããªããã°ã
NoSectionErrorãéåºããŸãããªãã·ã§ã³ãååšããŠåé€ãããã°ãTrueãè¿ããŸããããã§ãªããã°Falseãè¿ããŸãã
- remove_section(section)¶
æå®ããã section ãèšå®ããåé€ããŸããã»ã¯ã·ã§ã³ãå®éã«ååšããã°ã
Trueãè¿ããŸããããã§ãªããã°Falseãè¿ããŸãã
- optionxform(option)¶
å ¥åãã¡ã€ã«ã«çŸããããŸãã¯ã¯ã©ã€ã¢ã³ãã³ãŒãã§æž¡ããããªãã·ã§ã³å option ãå éšæ§é ã§å®éã«äœ¿ããã圢åŒã«å€æããŸããããã©ã«ãã®å®è£ ã§ã¯ option ã®å°æåçãè¿ããŸããæŽŸçã¯ã©ã¹ã§ãããäžæžãããããã¯ã©ã€ã¢ã³ãã³ãŒãã§ã€ã³ã¹ã¿ã³ã¹äžã®ãã®ååã®å±æ§ãèšå®ããŠããã®åäœã«åœ±é¿ãäžããããšãã§ããŸãã
ãã®ã¡ãœããã䜿ãããã«ããŒãµãŒã掟çã¯ã©ã¹åãããå¿ èŠã¯ãªããã€ã³ã¹ã¿ã³ã¹äžã§ããããæåååŒæ°ããšã£ãŠæååãè¿ã颿°ã«èšå®ã§ããŸããäŸãã°ãããã
strã«èšå®ãããšããªãã·ã§ã³åã«å€§æåå°æåã®åºå¥ãã€ããããŸã:cfgparser = ConfigParser() cfgparser.optionxform = str
ãªããèšå®ãã¡ã€ã«ãèªã¿èŸŒããšãããªãã·ã§ã³åã®åšãã®ç©ºçœã¯
optionxform()ãåŒã³åºãããåã«åãé€ãããŸãã
- configparser.UNNAMED_SECTION¶
A special object representing a section name used to reference the unnamed section (see Unnamed Sections).
RawConfigParser ãªããžã§ã¯ã¶
- class configparser.RawConfigParser(defaults=None, dict_type=dict, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation(), converters={}, allow_unnamed_section=False)¶
Legacy variant of the
ConfigParser. It has interpolation disabled by default and allows for non-string section names, option names, and values via its unsafeadd_sectionandsetmethods, as well as the legacydefaults=keyword argument handling.ããŒãžã§ã³ 3.2 ã§å€æŽ: allow_no_value, delimiters, comment_prefixes, strict, empty_lines_in_values, default_section ããã³ interpolation ã远å ãããŸããã
ããŒãžã§ã³ 3.5 ã§å€æŽ: converters åŒæ°ã远å ãããŸããã
ããŒãžã§ã³ 3.8 ã§å€æŽ: The default dict_type is
dict, since it now preserves insertion order.ããŒãžã§ã³ 3.13 ã§å€æŽ: The allow_unnamed_section argument was added.
泚é
代ããã«å éšã«ä¿åããå€ã®åãæ€æ»ãã
ConfigParserã䜿ãããšãæ€èšããŠãã ãããè£éãæãŸãªãå ŽåãConfigParser(interpolation=None)ã䜿çšã§ããŸãã- add_section(section)¶
Add a section named section or
UNNAMED_SECTIONto the instance.If the given section already exists,
DuplicateSectionErroris raised. If the default section name is passed,ValueErroris raised. IfUNNAMED_SECTIONis passed and support is disabled,UnnamedSectionDisabledErroris raised.section ã®åã¯æ€æ»ãããªãããããŠãŒã¶ãŒã¯éæååã®ååä»ãã»ã¯ã·ã§ã³ãäœãããšãã§ããŸãããã®æ¯ãèãã¯ãµããŒããããŠããããå éšãšã©ãŒãèµ·ããå¯èœæ§ããããŸãã
ããŒãžã§ã³ 3.14 ã§å€æŽ: Added support for
UNNAMED_SECTION.- set(section, option, value)¶
äžããããã»ã¯ã·ã§ã³ãååšããŠããã°ããªãã·ã§ã³ãæå®ãããå€ã«èšå®ããŸããã»ã¯ã·ã§ã³ãååšããªããã°
NoSectionErrorãçºçãããŸããRawConfigParser(ããã㯠raw ãã©ã¡ãŒã¿ãã»ããããConfigParser) ãæåååã§ãªãå€ã® å éšçãª æ ŒçŽå ŽæãšããŠäœ¿ãããšã¯å¯èœã§ããããã¹ãŠã®æ©èœ (眮æããã¡ã€ã«ãžã®åºåãå«ã) ããµããŒããããã®ã¯æååãå€ãšããŠäœ¿ã£ãå Žåã ãã§ãããŠãŒã¶ãŒã¯ããã®ã¡ãœããã䜿ã£ãŠéæååã®å€ãããŒã«ä»£å ¥ã§ããŸãããã®æ¯ãèãã¯ãµããŒããããŠããããérawã¢ãŒãã§ã®å€ã®ååŸãããã¡ã€ã«ãžã®æžãåºãã詊ã¿ãéã«ãšã©ãŒã®åå ãšãªãããŸãããã®ãããªä»£å ¥ãèš±ããªã ãããã³ã°ãããã³ã«APIã䜿çšããŠãã ããã
äŸå€Â¶
- exception configparser.Error¶
Base class for all other
configparserexceptions.
- exception configparser.NoSectionError¶
æå®ããã»ã¯ã·ã§ã³ãèŠã€ãããªãã£ãæã«èµ·ããäŸå€ã§ãã
- exception configparser.DuplicateSectionError¶
Exception raised if
add_section()is called with the name of a section that is already present or in strict parsers when a section if found more than once in a single input file, string or dictionary.ããŒãžã§ã³ 3.2 ã§å€æŽ: Added the optional source and lineno attributes and parameters to
__init__().
- exception configparser.DuplicateOptionError¶
strict ãªããŒãµãŒã§ãåäžã®å ¥åãã¡ã€ã«ãæååãèŸæžäžã«åããªãã·ã§ã³ãè€æ°åçŸãããšãã«éåºãããäŸå€ã§ããããã¯ãã¹ã¹ãã«ã倧æåå°æåã®åºå¥ã«é¢ä¿ãããšã©ãŒãäŸãã°èŸæžã®äºã€ã®ããŒãåã倧æåå°æåã®åºå¥ã®ãªãèšå®ããŒã衚ãããšããææããŸãã
- exception configparser.NoOptionError¶
æå®ããããªãã·ã§ã³ãæå®ãããã»ã¯ã·ã§ã³ã«èŠã€ãããªããšãã«éåºãããäŸå€ã§ãã
- exception configparser.InterpolationError¶
æååã®è£éäžã«åé¡ãèµ·ããæã«çºçããäŸå€ã®åºåºã¯ã©ã¹ã§ãã
- exception configparser.InterpolationDepthError¶
ç¹°ãè¿ãã®åæ°ã
MAX_INTERPOLATION_DEPTHãè¶ ããããã«æååè£éãå®äºããªãã£ããšãã«éåºãããäŸå€ã§ããInterpolationErrorã®æŽŸçã¯ã©ã¹ã§ãã
- exception configparser.InterpolationMissingOptionError¶
InterpolationErrorã®æŽŸçã¯ã©ã¹ã§ãå€ãåç §ããŠãããªãã·ã§ã³ãèŠã€ãããªãå Žåã«çºçããäŸå€ã§ãã
- exception configparser.InterpolationSyntaxError¶
眮æããªããããœãŒã¹ããã¹ããèŠæ±ãããææ³ãæºãããªããšãã«éåºãããäŸå€ã§ãã
InterpolationErrorã®æŽŸçã¯ã©ã¹ã§ãã
- exception configparser.MissingSectionHeaderError¶
ã»ã¯ã·ã§ã³ããããæããªããã¡ã€ã«ãæ§æè§£æããããšããæã«èµ·ããäŸå€ã§ãã
- exception configparser.ParsingError¶
ãã¡ã€ã«ã®æ§æè§£æäžã«ãšã©ãŒãèµ·ããå Žåã«çºçããäŸå€ã§ãã
ããŒãžã§ã³ 3.12 ã§å€æŽ: The
filenameattribute and__init__()constructor argument were removed. They have been available using the namesourcesince 3.2.
- exception configparser.MultilineContinuationError¶
Exception raised when a key without a corresponding value is continued with an indented line.
Added in version 3.13.
- exception configparser.UnnamedSectionDisabledError¶
Exception raised when attempting to use the
UNNAMED_SECTIONwithout enabling it.Added in version 3.14.
- exception configparser.InvalidWriteError¶
Exception raised when an attempted
ConfigParser.write()would not be parsed accurately with a futureConfigParser.read()call.Ex: Writing a key beginning with the
ConfigParser.SECTCREpattern would parse as a section header when read. Attempting to write this will raise this exception.Added in version 3.14.
èæ³š