Python Argparse Module
The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages.
Importing the Module
import argparse
Basic Usage
import argparse
# Create the parser
parser = argparse.ArgumentParser(description='Process some integers.')
# Add arguments
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
# Parse arguments
args = parser.parse_args()
# Use the arguments
print(args.accumulate(args.integers))
Positional vs Optional Arguments
- Positional arguments: Arguments that are required and must be provided in a specific order (unless
nargsis used). - Optional arguments: Arguments typically starting with
-or--(e.g.,--verbose).
parser.add_argument('filename', help='The file to process')
parser.add_argument('--verbose', '-v', action='store_true', help='Enable verbose output')
Auto-generated Help
Running the script with -h or --help will display the help message defined by the arguments.