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 json module 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, デフォルト倀: False

    Some 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 configparser behaviour matched comment_prefixes=('#',';') and inline_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, デフォルト倀: True

    When set to True, the parser will not allow for any section or option duplicates while reading from a single source (using read_file(), read_string() or read_dict()). It is recommended to use strict parsers in new applications.

    バヌゞョン 3.2 で倉曎: In previous versions of configparser behaviour matched strict=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(), and getboolean() 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 add getdecimal() on both the parser object and all section proxies. In other words, it will be possible to write both parser_instance.getdecimal('section', 'key', fallback=0) and parser_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 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 匕数を通しおカスタムハンドラを䞎えるこずでカスタマむズできたす。 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 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

バヌゞョン 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 MultilineContinuationError when allow_no_value is True, 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 name attribute, 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).

configparser.MAX_INTERPOLATION_DEPTH¶

The maximum depth for recursive interpolation for get() when the raw parameter is false. This is relevant only when the default interpolation is used.

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 unsafe add_section and set methods, as well as the legacy defaults= 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_SECTION to the instance.

If the given section already exists, DuplicateSectionError is raised. If the default section name is passed, ValueError is raised. If UNNAMED_SECTION is passed and support is disabled, UnnamedSectionDisabledError is 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 configparser exceptions.

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 filename attribute and __init__() constructor argument were removed. They have been available using the name source since 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_SECTION without enabling it.

Added in version 3.14.

exception configparser.InvalidWriteError¶

Exception raised when an attempted ConfigParser.write() would not be parsed accurately with a future ConfigParser.read() call.

Ex: Writing a key beginning with the ConfigParser.SECTCRE pattern would parse as a section header when read. Attempting to write this will raise this exception.

Added in version 3.14.

脚泚