The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse figures out how to parse those out of sys.argv. The module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.
Key Components of argparse
ArgumentParser Object
This is the main entry point for the argument parsing system. It contains methods for adding arguments and parsing them.
add_argument() Method
This method is used to specify which command-line options the program is expecting.
parse_args() Method
This method is called to parse the arguments provided by the user at the command line.
Basic Example
Here’s a step-by-step example of how to use argparse:
1. Import the Module
First, you need to import the argparse module:
import argparse
2. Create a Parser Object
You create an ArgumentParser object which will hold all the information necessary to parse the command line into Python data types:
parser.add_argument('filename', help='Name of the file to process')
parser.add_argument('-v', '--verbose', action='store_true', help='Increase output verbosity')
parser.add_argument('-c', '--count', type=int, help='Number of times to repeat the message')
args = parser.parse_args()
print(f"Filename: {args.filename}")
if args.verbose:
print("Verbosity turned on")
if args.count:
print(f"Count: {args.count}")
import argparse
# Create the parser
parser = argparse.ArgumentParser(description="Example Argument Parser")
# Add arguments
parser.add_argument('filename', help='Name of the file to process')
parser.add_argument('-v', '--verbose', action='store_true', help='Increase output verbosity')
parser.add_argument('-c', '--count', type=int, help='Number of times to repeat the message')
# Parse the arguments
args = parser.parse_args()
# Access the arguments
print(f"Filename: {args.filename}")
if args.verbose:
print("Verbosity turned on")
if args.count:
print(f"Count: {args.count}")