升级 optparse 代码 ¶
最初,
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.
-
Allowing alternative option prefixes like
+and/. -
Handling zero-or-more and one-or-more style arguments.
-
Producing more informative usage messages.
-
Providing a much simpler interface for custom
typeandaction.
A partial upgrade path from
optparse
to
argparse
:
-
Replace all
optparse.OptionParser.add_option()calls withArgumentParser.add_argument()调用。 -
替换
(options, args) = parser.parse_args()withargs = parser.parse_args()and add additionalArgumentParser.add_argument()calls for the positional arguments. Keep in mind that what was previously calledoptions, now in theargparsecontext is calledargs. -
替换
optparse.OptionParser.disable_interspersed_args()通过使用parse_intermixed_args()而不是parse_args(). -
Replace callback actions and the
callback_*keyword arguments withtypeoraction自变量。 -
Replace string names for
typekeyword arguments with the corresponding type objects (e.g. int, float, complex, etc). -
替换
optparse.ValueswithNamespaceandoptparse.OptionErrorandoptparse.OptionValueErrorwithArgumentError. -
Replace strings with implicit arguments such as
%defaultor%progwith the standard Python syntax to use dictionaries to format strings, that is,%(default)sand%(prog)s. -
Replace the OptionParser constructor
versionargument with a call toparser.add_argument('--version', action='version', version='<the version>').