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_*
キーワード引数をtype
やaction
引数に置き換える。type
キーワード引数に渡していた文字列の名前を、それに応じたオブジェクト (例: int, float, complex, ...) に置き換える。optparse.Values
をNamespace
に置き換え、optparse.OptionError
とoptparse.OptionValueError
をArgumentError
に置き換える。%default
や%prog
などの暗黙の引数を含む文字列を、%(default)s
や%(prog)s
などの、通常の Python で辞書を使う場合のフォーマット文字列に置き換える。OptionParser のコンストラクターの
version
引数を、parser.add_argument('--version', action='version', version='<the version>')
に置き換える