PEP 389: argparse - 新しいコマンドラインparseモジュール
==========================================================

原文: http://www.python.org/dev/peps/pep-0389/

訳注: argparseの公式ドキュメントは
http://argparse.googlecode.com/svn/trunk/doc/index.html

+----------------+--------------------------------------------+ 
| PEP            | 389                                        |
+----------------+--------------------------------------------+ 
| Title          | argparse - New Command Line Parsing Module |
+----------------+--------------------------------------------+ 
| Version        | 78618                                      |
+----------------+--------------------------------------------+ 
| Last-Modified  | 2010-03-03 03:55:24 +0100(Wed, 03 Mar 2010)|
+----------------+--------------------------------------------+ 
| Author         | Steven Bethard <steven.bethard@gmail.com>  |
+----------------+--------------------------------------------+ 
| Status         | Accepted                                   |
+----------------+--------------------------------------------+ 
| Type           | Standards Track                            |
+----------------+--------------------------------------------+ 
| Content-Type   | text/x-rst                                 |
+----------------+--------------------------------------------+ 
| Created        | 25-Sep-2009                                |
+----------------+--------------------------------------------+ 
| Python-Version | 2.7 and 3.2                                |
+----------------+--------------------------------------------+ 
| Post-History   | 27-Sep-2009, 24-Oct-2009                   |
+----------------+--------------------------------------------+ 


.. Acceptance
   ==========

承認
----------

.. This PEP was approved by Guido on python-dev on February 21, 2010 [17]_.

このPEPはGuidoによって、2010年4月21日のpython-devにて承認されました。 [17]_


.. Abstract
   ------==

概要
--------

.. This PEP proposes inclusion of the argparse [1]_ module in the Python
   standard library in Python 2.7 and 3.2.

このPEPでは、Python 2.7と3.2で標準ライブラリに加わったargparse [1]_ モ
ジュールに関して説明します。


.. Motivation
   ------====

モチベーション
--------------

.. The argparse module is a command line parsing library which provides
   more functionality than the existing command line parsing modules in
   the standard library, getopt [2]_ and optparse [3]_. It includes
   support for positional arguments (not just options), subcommands,
   required options, options syntaxes like "/f" and "+rgb", zero-or-more
   and one-or-more style arguments, and many other features the other
   two lack.

argparseモジュールは既存のコマンドライン引数を解釈するモジュールである
getopt [2]_ とoptparse [3]_ よりも高機能なparseライブラリです。argparseは、
単なるオプションだけでなく固定引数(positional argument)、サブコマンド、必
須オプション、"/f"や"+rgb"といったオプション文法、0以上や1以上という形式
の引数、その他getoptとoptparseが持っていない多数の機能を提供します。

.. The argparse module is also already a popular third-party replacement
   for these modules. It is used in projects like IPython (the Scipy
   Python shell) [4]_, is included in Debian testing and unstable [5]_,
   and since 2007 has had various requests for its inclusion in the
   standard library [6]_ [7]_ [8]_. This popularity suggests it may be
   a valuable addition to the Python libraries.

argparseモジュールはこれらのモジュールを置き換えるサードパーティ製のモ
ジュールとしてすでに人気があります。argparseはIPython(Scipy Python
Shell) [4]_ で使われており、Debianのtestingとusntable [5]_ に含まれてお
り、2007年から標準ライブラリに組み込むようたくさんのリクエストを受け取っ
て来ました [6]_ [7]_ [8]_ 。これはPythonのライブラリに追加する価値がある
ことを示唆しています。


.. Why aren't getopt and optparse enough?
   ======================================

なぜgetoptとoptparseは十分ではないの?
---------------------------------------

.. One argument against adding argparse is that thare are "already two
   different option parsing modules in the standard library" [9]_. The
   following is a list of features provided by argparse but not present
   in getopt or optparse:

argparseに対する議論の一つとして「すでにもう二つの異なるOptionパーザがあ
るじゃないか [9]_ 」というものがあります。以下にargparseにはあるが他の
getoptとoptparseにはない機能のリストを記します。

.. * While it is true there are two *option* parsing libraries, there
    are no full command line parsing libraries -- both getopt and
    optparse support only options and have no support for positional
    arguments. The argparse module handles both, and as a result, is
    able to generate better help messages, avoiding redundancies like
    the ``usage=`` string usually required by optparse.

* 既に二つの*option* パーザライブラリがあることは確かですが、完全なコマン
  ドラインパーズライブラリはありません。getoptとoptparseの両方とも、
  optionしかサポートしておらず、固定引数(positional argument)をサポートし
  ていません。argparseは両方を扱うことができ、結果として、より良いヘルプ
  メッセージを生成でき、optparseで必要になってくる ``usage=`` 文字列といっ
  た冗長な記述を避けられます。

.. * The argparse module values practicality over purity. Thus, argparse
    allows required options and customization of which characters are
    used to identify options, while optparse explicitly states "the
    phrase 'required option' is self-contradictory" and that the option
    syntaxes ``-pf``, ``-file``, ``+f``, ``+rgb``, ``/f`` and ``/file``
    "are not supported by optparse, and they never will be".

* argparseモジュールは純正よりも実用性を評価します。従って、optparseが
  「 'required option'は自己矛盾であり、 ``-pf``, ``-file``, ``+f``,
  ``+rgb``, ``/f``, ``/file`` はoptparseでサポートされず、今後もサポートさ
  れない」と明確に記載されているのと異なり、argparseは必要となるオプショ
  ンとオプションを識別するのに使われる文字のカスタマイズができます。

.. * The argparse module allows options to accept a variable number of
    arguments using ``nargs='?'``, ``nargs='*'`` or ``nargs='+'``. The
    optparse module provides an untested recipe for some part of this
    functionality [10]_ but admits that "things get hairy when you want
    an option to take a variable number of arguments."

* argparseは ``nargs='?'``, ``nargs='*'`` あるいは ``nargs='+'`` を使って
  可変長引数を記述できます。optparseはこの機能の一部をテストされていない
  レシピを使って提供していますが [10]_ 、「可変長引数を使おうとするとやば
  いことになりかねないよ」と認めています。

.. * The argparse module supports subcommands, where a main command line
    parser dispatches to other command line parsers depending on the
    command line arguments. This is a common pattern in command line
    interfaces, e.g. ``svn co`` and ``svn up``.

* argparseはサブコマンドをサポートしています。これは、主となるコマンドラ
  インパーザが依存する引数を他のコマンドラインパーザに送ります。これは、
  コマンドラインインタフェースではよく使われています。 例: ``svn co`` や
  ``svn up``


.. Why isn't the functionality just being added to optparse?
   =========================================================

optparseに機能を追加するのではなぜだめなの?
-----------------------------------------------------

.. Clearly all the above features offer improvements over what is
   available through optparse. A reasonable question then is why these
   features are not simply provided as patches to optparse, instead of
   introducing an entirely new module. In fact, the original development
   of argparse intended to do just that, but because of various fairly
   constraining design decisions of optparse, this wasn't really
   possible. Some of the problems included:

明らかに、以上述べてきた機能追加はoptparseに追加して実現できる許容量を
越えています。利にかなった質問は、これらの機能はまったく新しいモジュー
ルとしてではなく、なぜ単純にoptparseへのpatchとして提供されないのですか、
です。事実、argparseの開発初期段階はpatchとして行われていたのですが、
optparseの設計からくるさまざまな制約により、これは不可能だったのです。
以下に示すいくつかの問題がありました。

.. * The optparse module exposes the internals of its parsing
     algorithm.  In particular, ``parser.largs`` and ``parser.rargs``
     are guaranteed to be available to callbacks [11]_. This makes it
     extremely difficult to improve the parsing algorithm as was
     necessary in argparse for proper handling of positional arguments
     and variable length arguments. For example, ``nargs='+'`` in
     argparse is matched using regular expressions and thus has no
     notion of things like ``parser.largs``.

* optparseモジュールは内部のパースアルゴリズムを公開しています。特に、
  ``parser.largs`` と ``parser.rargs`` はコールバックがあることを前提とし
  ています [11]_ 。このことは、固定引数や可変長引数に対応するために
  argparseでパースアルゴリズムを改良することを阻害しています。例えば、
  argparseで ``nargs='+'`` を使って正規表現にマッチさせる時は、
  ``parser.largs`` などを使う意図はありません。(訳注:訳に自信なし)

.. * The optparse extension APIs are extremely complex. For example,
    just to use a simple custom string-to-object conversion function,
    you have to subclass ``Option``, hack class attributes, and then
    specify your custom option type to the parser, like this::

* optparseの拡張APIは非常に複雑です。例えば、簡単なstringからobjectへと
  変換する自作の関数を使おうとするときでも、 ``Option`` サブクラスを作
  り、クラス変数をいじり、自作のオプションタイプをparserに指定する必要
  があるのです。例を示します。::

    class MyOption(Option):
        TYPES = Option.TYPES + ("mytype",)
        TYPE_CHECKER = copy(Option.TYPE_CHECKER)
        TYPE_CHECKER["mytype"] = check_mytype
    parser = optparse.OptionParser(option_class=MyOption)
    parser.add_option("-m", type="mytype")

..  For comparison, argparse simply allows conversion functions to be
    used as ``type=`` arguments directly, e.g.::

  比較すると、argparseは単に変換関数を ``type=`` 引数に直接与えるだけで済み
  ます。 :: 

    parser = argparse.ArgumentParser()
    parser.add_option("-m", type=check_mytype)

..  But given the baroque customization APIs of optparse, it is
    unclear how such a feature should interact with those APIs, and it
    is quite possible that introducing the simple argparse API would
    break existing custom Option code.

  与えられたoptparseの古典的なカスタムAPIでは、このような機能がこれらの
  APIをどのように使えばいいのか不明確です。そのため、単純なargparseのAPI
  を導入すると、既存の自作のOptionコードを壊す可能性が高いです。

.. * Both optparse and argparse parse command line arguments and
    assign them as attributes to an object returned by ``parse_args``.
    However, the optparse module guarantees that the ``take_action``
    method of custom actions will always be passed a ``values`` object
    which provides an ``ensure_value`` method [12]_, while the
    argparse module allows attributes to be assigned to any object,
    e.g.::

* optparseとargparseは両方共コマンドラインの引数をパーズし、
  ``parse_args`` によって返されたオブジェクトの属性を設定します。しかし、
  optparseモジュールは自作のアクションである ``take_action`` メソッドに
  ``ensure_value`` メソッドを持つ ``values`` オブジェクトが常に渡されるこ
  とを前提としています [12]_ 。一方、argparseはどんなオブジェクトにでも属
  性を設定することができます。例 ::
  
    foo_object = ...
    parser.parse_args(namespace=foo_object)
    foo_object.some_attribute_parsed_from_command_line
  
..  Modifying optparse to allow any object to be passed in would be
    difficult because simply passing the ``foo_object`` around instead
    of a ``Values`` instance will break existing custom actions that
    depend on the ``ensure_value`` method.

  optparseをどんなオブジェクトでも受け入れるように変更することは難しいこ
  とでした。なぜなら、単に ``Values`` インスタンスの代わりに
  ``foo_object`` を渡すことは ``ensure_value`` メソッドに依存している既存
  の自作アクションを壊すからです。

.. Because of issues like these, which made it unreasonably difficult
   for argparse to stay compatible with the optparse APIs, argparse
   was developed as an independent module. Given these issues, merging
   all the argparse features into optparse with no backwards
   incompatibilities seems unlikely.

このような問題により、argparseがoptparse APIと互換性を保ったままにする
ことは難しく、argparseは独立したモジュールとして開発されました。付け加
えると、同じ理由によりargparseの全ての機能を後方互換性を保ったまま
optparseに入れることは考えられません。


.. Deprecation of optparse
  =======================

optparseの廃止
-----------------------

.. Because all of optparse's features are available in argparse, the
   optparse module will be deprecated. However, because of the
   widespread use of optparse, the deprecation strategy contains only
   documentation changes and warnings that will not be visible by
   default:

argparseで、optparseの全ての機能が実現されているため、optparseモジュール
は将来的に廃止されます。しかし、optparseは広く使用されているため、廃止の
道筋は単に文書の変更だけであり、標準では警告は表示されません。

.. * Python 2.7+ and 3.2+ -- The following note will be added to the
..  optparse documentation:
  
..    The optparse module is deprecated and will not be developed
      further; development will continue with the argparse module.

* Python 2.7以降と3.2以降 -- optparseの文章に以下の注意書きが付け加えら
  れます。
    
    optparseモジュールは廃止され、以降開発されません。以降の開発は
    argparseモジュールで継続されます。

.. * Python 2.7+ -- If the Python 3 compatibility flag, ``-3``, is
    provided at the command line, then importing optparse will issue a
    DeprecationWarning. Otherwise no warnings will be issued.

* Python 2.7以降 -- もしPython 3の互換性フラグ(``-3``)が与えられた場合、
  optparseはDeprecationWarningという警告を出します。そうでなければ、警告
  はなにも出ません。

.. * Python 3.2+ -- Importing optparse will issue a
     PendingDeprecationWarning, which is not displayed by default.

* Python 3.2以上 -- optparseをimportすると、PendingDeprecationWarningと
  いう、標準では表示されない警告が出ます。

.. Note that no removal date is proposed for optparse.

optparseが削除される日付に関してはなにも決まっていないことに注意してくだ
さい。

.. Updates to getopt documentation
   ===============================

getoptの文書の更新
-------------------------------

.. The getopt module will not be deprecated. However, its
  documentation will be updated to point to argparse in a couple of
  places. At the top of the module, the following note will be added:
    The getopt module is a parser for command line options whose API is
    designed to be familiar to users of the C getopt function.  Users
    who are unfamiliar with the C getopt function or who would like to
    write less code and get better help and error messages should
    consider using the argparse module instead.

getoptモジュールは廃止されません。しかし、その文書のいくつかの場所では
argparseを示すように更新されます。モジュールの先頭には以下の注意書きが
付け加えられます。 ::


  getoptモジュールはC言語のgetopt関数のAPIに慣れ親しんだユーザのために作
  られたコマンドラインオプションのパーズモジュールです。C言語のgetopt関数
  に不慣れな、あるいは少ないコード量でより良いヘルプとエラーメッセージを
  得たいユーザは、代わりにargparseモジュールを使ってください。

.. Additionally, after the final getopt example, the following note
   will be added:
   Note that an equivalent command line interface could be produced with less code by using the argparse module::

さらに、最後のgetoptの例の後に、以下の注意書きが付け加えられます。 ::


  少ないコード量で同等のコマンドラインインタフェースが、argparseモジュールを使うことで得られます。
  
    import argparse

    if __name__ == '__main__':
        parser = argparse.ArgumentParser()
        parser.add_argument('-o', '--output')
        parser.add_argument('-v', dest='verbose', action='store_true')
        args = parser.parse_args()
        # ... do something with args.output ...
        # ... do something with args.verbose ..


.. Deferred: string formatting
   ===========================

延期: 文字列フォーマット
---------------------------

.. The argparse module supports Python from 2.3 up through 3.2 and as
   a result relies on traditional ``%(foo)s`` style string
   formatting. It has been suggested that it might be better to use
   the new style ``{foo}`` string formatting [13]_. There was some
   discussion about how best to do this for modules in the standard
   library [14]_ and several people are developing functions for
   automatically converting %-formatting to {}-formatting [15]_
   [16]_. When one of these is added to the standard library, argparse
   will use them to support both formatting styles.

argparseモジュールはPython 2.3から3.2までサポートしますが、そのため、伝統
的な ``%(foo)s`` 形式の文字列フォーマットに依存します。これは新しい形式の
``{foo}`` フォーマットを使うように推奨されています [13]_ 。標準ライブラリ
ではこの問題について議論され [14]_ 、何人かは%形式から{}形式に自動的に変
換する機能を開発しています [15]_  [16]_ 。この変換機能が標準ライブラリに付
け加えられた時には、argparseもこの両方のフォーマット形式をサポートします。

.. Rejected: getopt compatibility methods
   ======================================

getopt互換のメソッドは取り除かれました
-----------------------------------------

.. Previously, when this PEP was suggesting the deprecation of getopt
   as well as optparse, there was some talk of adding a method like::

以前、このPEPがoptparseと同じくgetoptの廃止も提案したとき、以下のような
メソッドの追加に関する議論がありました。 ::

  ArgumentParser.add_getopt_arguments(options[, long_options])

.. However, this method will not be added for a number of reasons:

しかし、このメソッドはこれらの理由により追加されません。

.. * The getopt module is not being deprecated, so there is less need.

* getoptモジュールは廃止されないため、必要性は低いです。

.. * This method would not actually ease the transition for any getopt
    users who were already maintaining usage messages, because the API
    above gives no way of adding help messages to the arguments.

* このメソッドはすでにusageのメッセージを管理しているgetoptユーザが移行
  に使うには簡単ではありません。なぜならこのAPIは引数にヘルプメッセージ
  を追加する機能を提供していないからです。

.. * Some users of getopt consider it very important that only a
    single function call is necessary. The API above does not satisfy
    this requirement because both ``ArgumentParser()`` and
    ``parse_args()`` must also be called.

* getoptが想定しているユーザのうち何人かは、関数を一回だけ呼べばいいとい
  うことを重要視しています。このAPIでは ``ArgumentParser()`` と
  ``parse_args()`` の両方を呼ぶ必要があるため、この要求を満たせません。


.. Out of Scope: Various Feature Requests
   ======================================

スコープ外: 機能要求
--------------------------

.. Several feature requests for argparse were made in the discussion of
    this PEP:

argparseに対する機能要求のいくつかは、このPEPですでに議論されています。

.. * Support argument defaults from environment variables
   * Support argument defaults from configuration files
   * Support "foo --help subcommand" in addition to the currently
     supported "foo subcommand --help"

* 環境変数からデフォルトの引数を設定する機能
* 設定ファイルからデフォルトの引数を設定する機能
* 現在の"foo subcommand --help"に加えて"foo --help subcommand"を解釈する
  機能

.. These are all reasonable feature requests for the argparse module,
   but are out of the scope of this PEP, and have been redirected to
   the argparse issue tracker.

これらは全て正当な理由がある機能要求ですが、このPEPのスコープ外であり、
argparseのIssue Trackerで議論されます。

.. Discussion: sys.stderr and sys.exit
   ===================================

議論: sys.stderrとsys.exit
-----------------------------------

.. There were some concerns that argparse by default always writes to
   ``sys.stderr`` and always calls ``sys.exit`` when invalid arguments
   are provided. This is the desired behavior for the vast majority of
   argparse use cases which revolve around simple command line
   interfaces. However, in some cases, it may be desirable to keep
   argparse from exiting, or to have it write its messages to
   something other than ``sys.stderr``. These use cases can be
   supported by subclassing ``ArgumentParser`` and overriding the
   ``exit`` or ``_print_message`` methods. The latter is an
   undocumented implementation detail, but could be officially exposed
   if this turns out to be a common need.

argparseを使うと、標準では常に ``sys.stderr`` に書き出し、不正な引数が与
えられた時に常に ``sys.exit`` を呼んでいます。これは簡単なコマンドライン
インタフェースを提供するargparseのユースケースの大部分にとって期待された
振る舞いです。しかし、いくつかの場合では、argparseがexitしないようにして
欲しかったり、あるいは ``sys.stderr`` 以外に書き出して欲しかったりします。
このような場合、 ``ArgumentParser`` というサブクラスを作り、``exit`` や
``_print_message`` をオーバーライドすることで欲しい機能を実現できます。後
者は文書化されていない実相の詳細ですが、よく使われるようになれば公開しま
す。

参考文献
----------

.. [1] argparse
   (http://code.google.com/p/argparse/)

.. [2] getopt
   (http://docs.python.org/library/getopt.html)

.. [3] optparse
   (http://docs.python.org/library/optparse.html)

.. [4] argparse in IPython
   (http://mail.scipy.org/pipermail/ipython-dev/2009-April/005102.html)

.. [5] argparse in Debian
   (http://packages.debian.org/search?keywords=argparse)

.. [6] 2007-01-03 request for argparse in the standard library
   (http://mail.python.org/pipermail/python-list/2007-January/472276.html)

.. [7] 2009-06-09 request for argparse in the standard library
   (http://bugs.python.org/issue6247)

.. [8] 2009-09-10 request for argparse in the standard library
   (http://mail.python.org/pipermail/stdlib-sig/2009-September/000342.html)

.. [9] Fredrik Lundh response to [6]_
   (http://mail.python.org/pipermail/python-list/2007-January/1086892.html)

.. [10] optparse variable args
   (http://docs.python.org/library/optparse.html#callback-example-6-variable-arguments)

.. [11] parser.largs and parser.rargs
   (http://docs.python.org/library/optparse.html#how-callbacks-are-called)

.. [12] take_action values argument
   (http://docs.python.org/library/optparse.html#adding-new-actions)

.. [13] use {}-formatting instead of %-formatting
   (http://bugs.python.org/msg89279)

.. [14] transitioning from % to {} formatting
   (http://mail.python.org/pipermail/pytho

.. [15] Vinay Sajip's %-to-{} converter
   (http://gist.github.com/200936)

.. [16] Benjamin Peterson's %-to-{} converter
   (http://bazaar.launchpad.net/~gutworth/+junk/mod2format/files)

.. [17] Guido's approval
   (http://mail.python.org/pipermail/python-dev/2010-February/097839.html)


.. Copyright
   ==========

著作権
-------

..    This document has been placed in the public domain.

このドキュメントはパブリック・ドメインに属します。