Migrating optparse code to argparse

The argparse module offers several higher level features not natively provided by the optparse module, including:

  • 位置引数を扱う

  • Supporting subcommands.

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

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

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

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

Originally, the argparse module attempted to maintain compatibility with optparse. However, the fundamental design differences between supporting declarative command line option processing (while leaving positional argument processing to application code), and supporting both named options and positional arguments in the declarative interface mean that the API has diverged from that of optparse over time.

As described in Choosing an argument parsing library, applications that are currently using optparse and are happy with the way it works can just continue to use optparse.

Application developers that are considering migrating should also review the list of intrinsic behavioural differences described in that section before deciding whether or not migration is desirable.

For applications that do choose to migrate from optparse to argparse, the following suggestions should be helpful:

  • すべての 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>') に置き換える