The
argparse
module for parsing command-line arguments was added as a more powerful replacement for the optparse
module.
This means Python now supports three different modules for parsing command-line arguments:
getopt
, optparse
, and argparse
. The getopt
module closely resembles the C library’s getopt()
function, so it remains useful if you’re writing a Python prototype that will eventually be rewritten in C. optparse
becomes redundant, but there are no plans to remove it because there are many scripts still using it, and there’s no automated way to update these scripts. (Making the argparse
API consistent with optparse
’s interface was discussed but rejected as too messy and difficult.)
In short, if you’re writing a new script and don’t need to worry about compatibility with earlier versions of Python, use
argparse
instead of optparse
.
Here’s an example:
Unless you override it,
-h
and --help
switches are automatically added, and produce neatly formatted output:
As with
optparse
, the command-line switches and arguments are returned as an object with attributes named by the dest parameters:argparse
has much fancier validation than optparse
; you can specify an exact number of arguments as an integer, 0 or more arguments by passing '*'
, 1 or more by passing '+'
, or an optional argument with '?'
. A top-level parser can contain sub-parsers to define subcommands that have different sets of switches, as in svn commit
, svn checkout
, etc. You can specify an argument’s type as FileType
, which will automatically open files for you and understands that '-'
means standard input or output.
See also
argparse
documentation- The documentation page of the argparse module.
- Upgrading optparse code
- Part of the Python documentation, describing how to convert code that uses
optparse
. - PEP 389 - argparse - New Command Line Parsing Module
- PEP written and implemented by Steven Bethard.
No comments:
Post a Comment