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_*
キーワード引数を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>')
に置き換える