Migratingoptparse code toargparse¶
Theargparse module offers several higher level features not nativelyprovided by theoptparse module, including:
Handling positional arguments.
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.
Originally, theargparse module attempted to maintain compatibilitywithoptparse. However, the fundamental design differences betweensupporting declarative command line option processing (while leaving positionalargument processing to application code), and supporting both named optionsand positional arguments in the declarative interface mean that theAPI has diverged from that ofoptparse over time.
As described inChoosing an argument parsing library, applications that arecurrently usingoptparse and are happy with the way it works canjust continue to useoptparse.
Application developers that are considering migrating should also reviewthe list of intrinsic behavioural differences described in that sectionbefore deciding whether or not migration is desirable.
For applications that do choose to migrate fromoptparse toargparse,the following suggestions should be helpful:
Replace all
optparse.OptionParser.add_option()calls withArgumentParser.add_argument()calls.Replace
(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 previouslycalledoptions, now in theargparsecontext is calledargs.Replace
optparse.OptionParser.disable_interspersed_args()by usingparse_intermixed_args()instead ofparse_args().Replace callback actions and the
callback_*keyword arguments withtypeoractionarguments.Replace string names for
typekeyword arguments with the correspondingtype objects (e.g. int, float, complex, etc).Replace
optparse.ValueswithNamespaceandoptparse.OptionErrorandoptparse.OptionValueErrorwithArgumentError.Replace strings with implicit arguments such as
%defaultor%progwiththe 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='<theversion>').