The argparse module: a Python command line parser
The argparse module is an optparse-inspired command line parser that improves on optparse by:
- handling both optional and positional arguments
- supporting parsers that dispatch to sub-parsers
- producing more informative usage messages
- supporting actions that consume any number of command-line args
- allowing types and actions to be specified with simple callables instead of hacking class attributes like STORE_ACTIONS or CHECK_METHODS
as well as including a number of other more minor improvements on the optparse API.
Downloads
The argparse module is available in a few different formats:
- A single Python module, also available through the Browse Source link at the top of the page.
- A source distribution
- A Windows binary distribution
The latter two formats are hosted by the argparse home on the Python Package Index.
Documentation
- What makes argparse better than optparse? Check out the Argparse vs. Optparse page. This includes a bunch of examples, so if you want to get the flavor of the package, it's a great place to start.
- API documentation is available in the sections below, though if you've used optparse, most of the functionality should look familiar.
- The ArgumentParser constructor.
- The add_argument method.
- The add_argument_group method.
- The add_subparsers method.
- The set_defaults method.
- The parse_args method.
- The FileType factory.
- The ArgumentParser constructor.
Example Usage
The following simple example uses the argparse module to generate the command-line interface for a Python program that sums its command-line arguments and writes them to a log file:
import argparse import sys if __name__ == '__main__': # create the parser parser = argparse.ArgumentParser( description='Sum the integers on the command line.') # add the arguments parser.add_argument( 'integers', metavar='int', type=int, nargs='+', help='one of the integers to be summed') parser.add_argument( '--log', type=argparse.FileType('w'), default=sys.stdout, help='the file where the sum should be written ' '(default: write the sum to stdout)') # parse the command line args = parser.parse_args() # write out the sum args.log.write('%s\n' % sum(args.integers)) args.log.close()
Assuming the Python code above is saved into a file called scriptname.py, it can be run at the command line and provides useful help messages:
$ scriptname.py -h
usage: scriptname.py [-h] [--log LOG] int [int ...]
Sum the integers on the command line.
positional arguments:
int one of the integers to be summed
optional arguments:
-h, --help show this help message and exit
--log LOG the file where the sum should be written (default: write the sum
to stdout)
When run with the appropriate arguments, it writes the sum of the command-line integers to the specified log file:
$ scriptname.py --log=log.txt 1 1 2 3 5 8 $ more log.txt 20
For more examples and how to use the module, see the documentation section above.
Upgrading code from optparse
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 the new nargs= specifiers and better usage messges. When most everything in optparse had either been copy-pasted over or monkey-patched, it no longer seemed worthwhile to try to maintain the backwards compatibility.
A partial upgrade path from optparse to argparse:
- Replace all add_option() calls with add_argument() calls.
- Replace options, args = parser.parse_args() with args = parser.parse_args() and add additional add_argument calls for the positional arguments.
- Replace callback actions and the callable* keyword arguments with type=<callable> or action=<callable> arguments.
- Replace string names for type keyword arguments with the corresponding type objects (e.g. int, float, complex, etc).
- Replace Values with Namespace and OptionError/OptionValueError with ArgumentError.
- Replace strings with implicit arguments such as %default or %prog with the standard python syntax to use dictionaries to format strings, that is to say, %(default)s and %(prog)s.
Bugs and Feature Requests
You can report bugs and make feature requests through the Trac ticket system.
- Search for your bug or feature to see if there is already a ticket for it.
- Login to the guest account. Both the username and password are guest.
- Create a ticket. Please provide an email address so that you can be contacted if we need any more information. For bugs, please show both the problematic code and the error message it produced.
Development
Currently, Steven Bethard is the main developer and maintainer of the argparse module. If you have questions about how to achieve a particular effect, suggestions for improvements or are just interested in helping out, feel free to drop him an email.
