13.2. "ConfigParser" --- 設定ファイルの構文解析器
*************************************************

注釈: "ConfigParser" モジュールは Python 3 で "configparser" に改名
  されま した。 *2to3* ツールが自動的にソース内の import を修正します
  。

This module defines the class "ConfigParser".   The "ConfigParser"
class implements a basic configuration file parser language which
provides a structure similar to what you would find on Microsoft
Windows INI files.  You can use this to write Python programs which
can be customized by end users easily.

注釈: このライブラリでは、Windowsのレジストリ用に拡張された INI 文法
  はサポ ート *していません* 。

参考:

  "shlex" モジュール
     アプリケーション設定ファイルのフォーマットとして使える、Unix シェ
     ルに似たミニ言語の作成を支援します。

  "json" モジュール
     json モジュールは、同じ目的に利用できる JavaScript の文法のサブセ
     ットを実装しています。

設定ファイルは 1 つ以上のセクションからなり、セクションは "[section]"
ヘッダとそれに続く **RFC 822** 形式の "name: value" エントリからなって
います。(section 3.1.1 "LONG HEADER FIELDS" を参照) "name=value" とい
う形式も使えます。値の先頭にある空白文字は削除されるので注意してくださ
い。オプションの値には、同じセクションか "DEFAULT" セクションにある値
を参照するような書式化文字列を含めることができます。初期化時や検索時に
別のデフォルト値を与えることもできます。 "'#'" か "';'" ではじまる行は
無視され、コメントを書くために利用できます。

設定ファイルは、特定の文字 ("#" と ";") で始まるコメントを含んでいるこ
とがあります。コメントはある行の中に単独で書かれる場合もありますし、値
やセクション名のある行に書かれる場合もあります。後者がコメントとして認
識されるためには、その前に空白文字が入っている必要があります。 (後方互
換性のために、 "#" ではなく ";" で一行コメントを書いてください。)

最も高機能なクラス "SafeConfigParser" は置換機能をサポートします。これ
は同じセクション内の値や "DEFAULT" という特別なセクションの値を参照す
るフォーマット文字列を使うことができるという意味です。さらに初期化のと
きにデフォルトの値を追加することもできます。

例えば:

   [My Section]
   foodir: %(dir)s/whatever
   dir=frob
   long: this value continues
      in the next line

この場合 "%(dir)s" は変数 "dir" (この場合は "frob")に展開されます。参
照の展開は必要に応じて実行されます。

Default values can be specified by passing them into the
"ConfigParser" constructor as a dictionary.  Additional defaults  may
be passed into the "get()" method which will override all others.

Sections are normally stored in a built-in dictionary. An alternative
dictionary type can be passed to the "ConfigParser" constructor. For
example, if a dictionary type is passed that sorts its keys, the
sections will be sorted on write-back, as will be the keys within each
section.

class ConfigParser.RawConfigParser([defaults[, dict_type[, allow_no_value]]])

   基本的な設定オブジェクトです。 *defaults* が与えられた場合、オブジ
   ェクトに固有のデフォルト値がその値で初期化されます。 *dict_type* が
   与えられた場合、それが、セクションのリストの格納、セクション内のオ
   プションの格納、デフォルト値のために利用されます。 *allow_no_value*
   (デフォルト: "False") が真の時、値のないオプションが許可されます。
   この場合の値は "None" になります。

   このクラスは値の置換をサポートしません。

   全てのオプション名が "optionxform()" メソッドに渡されます。このメソ
   ッドのデフォルトの実装では、オプション名を小文字に変換します。

   バージョン 2.3 で追加.

   バージョン 2.6 で変更: *dict_type* が追加されました。

   バージョン 2.7 で変更: *dict_type* のデフォルトが
   "collections.OrderedDict" になりました。 *allow_no_value* が追加さ
   れました。

class ConfigParser.ConfigParser([defaults[, dict_type[, allow_no_value]]])

   "RawConfigParser" の派生クラスで値の置換を実装しており、 "get()" メ
   ソッドと "items()" メソッドに省略可能な引数を追加しています。
   *defaults* に含まれる値は "%()s" による値の置換に適当なものである必
   要があります。 *__name__* は組み込みのデフォルト値で、セクション名
   が含まれるので *defaults* で設定してもオーバーライドされます。

   置換で使われるすべてのオプション名は、ほかのオプション名への参照と
   同様に "optionxform()" メソッドを介して渡されます。 "optionxform()"
   のデフォルト実装を使うと、値 "foo %(bar)s" および "foo %(BAR)s" は
   同一になります。

   バージョン 2.3 で追加.

   バージョン 2.6 で変更: *dict_type* が追加されました。

   バージョン 2.7 で変更: *dict_type* のデフォルトが
   "collections.OrderedDict" になりました。 *allow_no_value* が追加さ
   れました。

class ConfigParser.SafeConfigParser([defaults[, dict_type[, allow_no_value]]])

   Derived class of "ConfigParser" that implements a more-sane variant
   of the magical interpolation feature.  This implementation is more
   predictable as well. New applications should prefer this version if
   they don't need to be compatible with older versions of Python.

   バージョン 2.3 で追加.

   バージョン 2.6 で変更: *dict_type* が追加されました。

   バージョン 2.7 で変更: *dict_type* のデフォルトが
   "collections.OrderedDict" になりました。 *allow_no_value* が追加さ
   れました。

exception ConfigParser.Error

   他の全ての configparser の例外の基底クラスです。

exception ConfigParser.NoSectionError

   指定したセクションが見つからなかった時に起きる例外です。

exception ConfigParser.DuplicateSectionError

   すでに存在するセクション名に対して "add_section()" が呼び出された際
   に起きる例外です。

exception ConfigParser.NoOptionError

   指定したオプションが指定したセクションに存在しなかった時に起きる例
   外です。

exception ConfigParser.InterpolationError

   文字列の置換中に問題が起きた時に発生する例外の基底クラスです。

exception ConfigParser.InterpolationDepthError

   "InterpolationError" の派生クラスで、文字列の置換回数が
   "MAX_INTERPOLATION_DEPTH" を越えたために完了しなかった場合に発生す
   る例外です。

exception ConfigParser.InterpolationMissingOptionError

   "InterpolationError" の派生クラスで、値が参照しているオプションが見
   つからない場合に発生する例外です。

   バージョン 2.3 で追加.

exception ConfigParser.InterpolationSyntaxError

   "InterpolationError" の派生クラスで、指定された構文で値を置換するこ
   とができなかった場合に発生する例外です。

   バージョン 2.3 で追加.

exception ConfigParser.MissingSectionHeaderError

   セクションヘッダを持たないファイルを構文解析しようとした時に起きる
   例外です。

exception ConfigParser.ParsingError

   ファイルの構文解析中にエラーが起きた場合に発生する例外です。

ConfigParser.MAX_INTERPOLATION_DEPTH

   The maximum depth for recursive interpolation for "get()" when the
   *raw* parameter is false.  This is relevant only for the
   "ConfigParser" class.

参考:

  "shlex" モジュール
     アプリケーション用の設定ファイルフォーマットとして使える、 Unix
     シェルライクなミニ言語の作成を支援します。


13.2.1. RawConfigParser オブジェクト
====================================

"RawConfigParser" クラスのインスタンスは以下のメソッドを持ちます:

RawConfigParser.defaults()

   インスタンス全体で使われるデフォルト値の辞書を返します。

RawConfigParser.sections()

   利用可能なセクションのリストを返します。 "DEFAULT" はこのリストに含
   まれません。

RawConfigParser.add_section(section)

   *section* という名前のセクションをインスタンスに追加します。同名の
   セクションが存在した場合、 "DuplicateSectionError" が発生します。
   "DEFAULT" (もしくは大文字小文字が違うもの)が渡された場合、
   "ValueError" が発生します。

RawConfigParser.has_section(section)

   指定したセクションがコンフィグレーションファイルに存在するかを返し
   ます。 "DEFAULT" セクションは存在するとみなされません。

RawConfigParser.options(section)

   *section* で指定したセクションで利用できるオプションのリストを返し
   ます。

RawConfigParser.has_option(section, option)

   与えられたセクションが存在してかつオプションが与えられていれば
   "True" を返し、そうでなければ "False" を返します。

   バージョン 1.6 で追加.

RawConfigParser.read(filenames)

   Attempt to read and parse a list of filenames, returning a list of
   filenames which were successfully parsed.  If *filenames* is a
   string or Unicode string, 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 a list 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 list 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 "readfp()" before calling "read()" for
   any optional files:

      import ConfigParser, os

      config = ConfigParser.ConfigParser()
      config.readfp(open('defaults.cfg'))
      config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])

   バージョン 2.4 で変更: 解析に成功したファイル名のリストを返します。

RawConfigParser.readfp(fp[, filename])

   *fp* で与えられるファイルかファイルのようなオブジェクトを読み込んで
   構文解析します("readline()" メソッドだけを使います)。もし
   *filename* が省略されて *fp* が "name" 属性を持っていれば
   *filename* の代わりに使われます。ファイル名の初期値は "<???>" です
   。

RawConfigParser.get(section, option)

   *section* の *option* 変数を取得します。

RawConfigParser.getint(section, option)

   *section* の *option* を整数として評価する関数です。

RawConfigParser.getfloat(section, option)

   *section* の *option* を浮動小数点数として評価する関数です。

RawConfigParser.getboolean(section, option)

   指定した *section* の *option* 値をブール値に型強制する便宜メソッド
   です。 *option* として受理できる値は、真 (True) としては ""1"" 、
   ""yes"" 、 ""true"" 、 ""on"" 、偽 (False) としては ""0"" 、 ""no""
   、 ""false"" 、 ""off"" です。これらの文字列値に対しては大文字小文
   字の区別をしません。その他の値の場合には "ValueError" を送出します
   。

RawConfigParser.items(section)

   与えられた *section* のそれぞれのオプションについて "(name, value)"
   ペアのリストを返します。

RawConfigParser.set(section, option, value)

   If the given section exists, set the given option to the specified
   value; otherwise raise "NoSectionError".  While it is possible to
   use "RawConfigParser" (or "ConfigParser" with *raw* parameters set
   to true) for *internal* storage of non-string values, full
   functionality (including interpolation and output to files) can
   only be achieved using string values.

   バージョン 1.6 で追加.

RawConfigParser.write(fileobject)

   設定を文字列表現に変換してファイルオブジェクトに書き出します。この
   文字列表現は "read()" で読み込むことができます。

   バージョン 1.6 で追加.

RawConfigParser.remove_option(section, option)

   指定された *section* から指定された *option* を削除します。セクショ
   ンが存在しなければ、 "NoSectionError" を起こします。存在するオプシ
   ョンを削除した時は "True" を、そうでない時は "False" を返します。

   バージョン 1.6 で追加.

RawConfigParser.remove_section(section)

   指定された *section* を設定から削除します。もし指定されたセクション
   が存在すれば "True" 、そうでなければ "False" を返します。

RawConfigParser.optionxform(option)

   入力ファイル中に見つかったオプション名か、クライアントコードから渡
   されたオプション名 *option* を、内部で利用する形式に変換します。デ
   フォルトでは *option* を全て小文字に変換した名前が返されます。サブ
   ルクラスではこの関数をオーバーライドすることでこの振舞いを替えるこ
   とができます。

   振舞いを替えるために ConfigParser を継承して新たにクラスを作る必要
   はありません、あるインスタンスのメソッドを文字列を引数に取る関数で
   置き換えることもできます。たとえば、このメソッドを "str()" に設定す
   ることで大小文字の差を区別するように変更することができます:

      cfgparser = ConfigParser()
      ...
      cfgparser.optionxform = str

   設定ファイルを読み込むときには、 "optionxform()" が呼ばれる前にオプ
   ション名の前後の空白文字が取り除かれることに注意してください。


13.2.2. ConfigParser オブジェクト
=================================

The "ConfigParser" class extends some methods of the "RawConfigParser"
interface, adding some optional arguments.

ConfigParser.get(section, option[, raw[, vars]])

   *section* の *option* 変数を取得します。このメソッドに渡される
   *vars* は辞書でなくてはいけません。 (もし渡されているならば) *vars*
   、 *section* 、 *defaults* の順に *option* が探されます。

   *raw* が真でない時には、全ての "'%'" 置換は展開されてから返されます
   。置換後の値はオプションと同じ順序で探されます。

ConfigParser.items(section[, raw[, vars]])

   指定した *section* 内の各オプションに対して、 "(name, value)" のペ
   アからなるリストを返します。省略可能な引数は "get()" メソッドと同じ
   意味を持ちます。

   バージョン 2.3 で追加.


13.2.3. SafeConfigParser オブジェクト
=====================================

The "SafeConfigParser" class implements the same extended interface as
"ConfigParser", with the following addition:

SafeConfigParser.set(section, option, value)

   もし与えられたセクションが存在している場合は、指定された値を与えら
   れたオプションに設定します。そうでない場合は "NoSectionError" を発
   生させます。 *value* は文字列 ("str" または "unicode") でなければな
   らず、そうでない場合には "TypeError" が発生します。

   バージョン 2.4 で追加.


13.2.4. 使用例
==============

設定ファイルを書き出す例:

   import ConfigParser

   config = ConfigParser.RawConfigParser()

   # When adding sections or items, add them in the reverse order of
   # how you want them to be displayed in the actual file.
   # In addition, please note that using RawConfigParser's and the raw
   # mode of ConfigParser's respective 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. SafeConfigParser 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', 'wb') 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')

To get interpolation, you will need to use a "ConfigParser" or
"SafeConfigParser":

   import ConfigParser

   config = ConfigParser.ConfigParser()
   config.read('example.cfg')

   # Set the third, optional argument of get to 1 if you wish to use raw mode.
   print config.get('Section1', 'foo', 0)  # -> "Python is fun!"
   print config.get('Section1', 'foo', 1)  # -> "%(bar)s is %(baz)s!"

   # The optional fourth argument is a dict with members that will take
   # precedence in interpolation.
   print config.get('Section1', 'foo', 0, {'bar': 'Documentation',
                                           'baz': 'evil'})

3 種類全ての ConfigParser クラスで、デフォルト値を利用できます。別にオ
プションが指定されていなかった場合、このデフォルト値は置換機能でも利用
されます:

   import ConfigParser

   # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
   config = ConfigParser.SafeConfigParser({'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!"

"opt_move" 関数は、オプションをセクション間で移動することができます:

   def opt_move(config, section1, section2, option):
       try:
           config.set(section2, option, config.get(section1, option, 1))
       except ConfigParser.NoSectionError:
           # Create non-existent section
           config.add_section(section2)
           opt_move(config, section1, section2, option)
       else:
           config.remove_option(section1, option)

いくつかの設定ファイルでは、値のない設定項目がある以外は
"ConfigParser" の文法と同じ文法になっています。コンストラクタの
*allow_no_value* 引数で、そのような値を許可することができます。

   >>> import ConfigParser
   >>> import io

   >>> sample_config = """
   ... [mysqld]
   ... user = mysql
   ... pid-file = /var/run/mysqld/mysqld.pid
   ... skip-external-locking
   ... old_passwords = 1
   ... skip-bdb
   ... skip-innodb
   ... """
   >>> config = ConfigParser.RawConfigParser(allow_no_value=True)
   >>> config.readfp(io.BytesIO(sample_config))

   >>> # Settings with values are treated as before:
   >>> config.get("mysqld", "user")
   'mysql'

   >>> # Settings without values provide None:
   >>> config.get("mysqld", "skip-bdb")

   >>> # Settings which aren't specified still raise an error:
   >>> config.get("mysqld", "does-not-exist")
   Traceback (most recent call last):
     ...
   ConfigParser.NoOptionError: No option 'does-not-exist' in section: 'mysqld'
