Upgrading optparse code

Originally, the argparse module had attempted to maintain compatibility with optparse. However, optparse was difficult to extend transparently, particularly with the changes required to support nargs= specifiers and better usage messages. When most everything in optparse had either been copy-pasted over or monkey-patched, it no longer seemed practical to try to maintain the backwards compatibility.

The argparse module improves on the optparse module in a number of ways including:

  • 位置引数を扱う

  • Supporting subcommands.

  • +, / のような代替オプションプレフィクスを許容する

  • zero-or-more スタイル、one-or-more スタイルの引数を扱う

  • より有益な使用方法メッセージの生成

  • カスタム type, カスタム action のために遥かに簡単なインターフェイスを提供する

A partial upgrade path from optparse to argparse:

  • すべての optparse.OptionParser.add_option() の呼び出しを、ArgumentParser.add_argument() の呼び出しに置き換える。

  • (options, args) = parser.parse_args()args = parser.parse_args() に置き換え、位置引数のために必要に応じて ArgumentParser.add_argument() の呼び出しを追加する。これまで options と呼ばれていたものが、argparse では args と呼ばれていることに留意してください。

  • optparse.OptionParser.disable_interspersed_args() を、parse_args() ではなく parse_intermixed_args() で置き換える。

  • コールバック・アクションと callback_* キーワード引数を typeaction 引数に置き換える。

  • type キーワード引数に渡していた文字列の名前を、それに応じたオブジェクト (例: int, float, complex, ...) に置き換える。

  • optparse.ValuesNamespace に置き換え、optparse.OptionErroroptparse.OptionValueErrorArgumentError に置き換える。

  • %default%prog などの暗黙の引数を含む文字列を、%(default)s%(prog)s などの、通常の Python で辞書を使う場合のフォーマット文字列に置き換える。

  • OptionParser のコンストラクターの version 引数を、parser.add_argument('--version', action='version', version='<the version>') に置き換える