Parsing arguments
When writing command-line tools, it's usually common to have it change behavior based on options provided to the executable. These options are usually available in sys.argv
together with the executable name, but parsing them is not as easy as it might seem, especially when multiple arguments must be supported. Also, when an option is malformed, it's usually a good idea to provide a usage message to inform the user about the right way to use the tool.
How to do it...
Perform the following steps for this recipe:
- The
argparse.ArgumentParser
object is the primary object in charge of parsing command-line options:
import argparse import operator import logging import functools parser = argparse.ArgumentParser( description='Applies an operation to one or more numbers' ) parser.add_argument("number", help="One or more numbers to perform an operation on.", nargs='+', type=int) parser.add_argument('-o', '--operation', ...