argparse
import argparse The argparse module is Python’s standard library for building command-line interfaces. It makes it easy to define what arguments your program expects, parse those arguments from sys.argv, automatically generate help messages, and handle errors when users provide invalid input. Before argparse, developers used optparse and getopt, but argparse supersedes both with a more powerful and flexible API.
The module works around an ArgumentParser object that serves as a container for all your argument definitions. You add arguments using add_argument(), then call parse_args() to extract values from the command line.
Creating a Parser
ArgumentParser()
The ArgumentParser constructor creates a new parser object. All arguments are keyword-only.
import argparse
parser = argparse.ArgumentParser(
prog='myapp',
description='What the program does',
epilog='Text shown after help output'
)
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
prog | str | derived from sys.argv | Program name shown in help messages |
description | str | None | Text displayed before argument help |
epilog | str | None | Text displayed after argument help |
parents | list | [] | List of ArgumentParser objects to inherit arguments from |
formatter_class | class | HelpFormatter | Class for customizing help output format |
prefix_chars | str | '-' | Characters that prefix optional arguments |
add_help | bool | True | Add -h/--help option automatically |
exit_on_error | bool | True | Exit with error message on invalid arguments |
suggest_on_error | bool | False | Suggest corrections for mistyped arguments |
color | bool | True | Use ANSI color in help/error output |
Defining Arguments
add_argument()
This method attaches an argument specification to the parser. It can define positional arguments, options that accept values, and boolean flags.
parser.add_argument('filename') # positional argument
parser.add_argument('-c', '--count') # option with short and long form
parser.add_argument('-v', '--verbose', action='store_true') # boolean flag
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
name_or_flags | str/list | — | Argument name or list of option strings |
action | str | 'store' | How to handle the argument (see below) |
nargs | int/str | None | Number of arguments to consume |
const | any | None | Constant value for certain actions/nargs |
default | any | None | Value if argument is absent |
type | callable | str | Type to convert argument value |
choices | sequence | None | Allowed values for the argument |
required | bool | False | Whether option must be provided |
help | str | None | Help text for the argument |
metavar | str | None | Name shown in usage messages |
dest | str | derived | Attribute name in Namespace object |
Action values:
'store'— Store the value (default)'store_const'— Store a constant value'store_true'/'store_false'— StoreTrue/False'append'— Append value to a list (allows multiple uses)'append_const'— Append constant to a list'count'— Count occurrences (useful for verbosity flags)'help'— Print help and exit'version'— Print version and exit
Parsing Arguments
parse_args()
This method parses the command-line arguments and returns a Namespace object with the parsed values.
args = parser.parse_args()
print(args.filename)
print(args.count)
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
args | list | sys.argv[1:] | Arguments to parse |
namespace | Namespace | None | Namespace to populate with values |
Returns: An argparse.Namespace object with attributes for each defined argument.
Examples
Basic positional and optional arguments
import argparse
parser = argparse.ArgumentParser(description='Process some files')
parser.add_argument('input_file', help='Input file path')
parser.add_argument('-o', '--output', help='Output file path')
parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose output')
args = parser.parse_args()
print(f"Input: {args.input_file}")
if args.output:
print(f"Output: {args.output}")
if args.verbose:
print("Verbose mode enabled")
Running the script:
$ python script.py data.txt
Input: data.txt
$ python script.py data.txt -o result.txt
Input: data.txt
Output: result.txt
$ python script.py data.txt --verbose -o out.txt
Input: data.txt
Output: out.txt
Verbose mode enabled
Type conversion and choices
import argparse
parser = argparse.ArgumentParser(description='Calculate statistics')
parser.add_argument('numbers', type=int, nargs='+', help='Numbers to process')
parser.add_argument('--operation', choices=['sum', 'avg', 'min', 'max'],
default='sum', help='Mathematical operation')
parser.add_argument('--precision', type=int, default=2, help='Decimal places')
args = parser.parse_args()
result = getattr(__import__('builtins'), args.operation)(args.numbers)
print(f"Result: {result:.{args.precision}f}")
$ python calc.py 10 20 30 40
Result: 100.00
$ python calc.py 10 20 30 40 --operation avg
Result: 25.00
$ python calc.py 10 20 --operation max
Result: 20.00
Subcommands
Argparse supports subcommands like git commit or docker run:
import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='command', help='Available commands')
# git commit
commit_parser = subparsers.add_parser('commit', help='Commit changes')
commit_parser.add_argument('-m', '--message', required=True, help='Commit message')
commit_parser.add_argument('--amend', action='store_true', help='Amend last commit')
# git log
log_parser = subparsers.add_parser('log', help='Show commit log')
log_parser.add_argument('-n', '--count', type=int, default=10, help='Number of commits')
args = parser.parse_args()
print(f"Command: {args.command}")
print(f"Args: {vars(args)}")
$ python git.py commit -m "Fix bug"
Command: commit
Args: {'command': 'commit', 'message': 'Fix bug', 'amend': False}
$ python git.py log -n 5
Command: log
Args: {'command': 'log', 'count': 5}
Custom types and validation
import argparse
import pathlib
def validate_port(value):
port = int(value)
if not 1 <= port <= 65535:
raise argparse.ArgumentTypeError(f"Port {port} is not in range 1-65535")
return port
parser = argparse.ArgumentParser()
parser.add_argument('--host', default='localhost', help='Server host')
parser.add_argument('--port', type=validate_port, default=8000, help='Server port')
parser.add_argument('--config', type=pathlib.Path, help='Config file path')
args = parser.parse_args()
print(f"Starting server at {args.host}:{args.port}")
Common Patterns
Mutual exclusion with argument groups
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('--verbose', action='store_true')
group.add_argument('--quiet', action='store_true')
Using parents to share arguments
import argparse
# Base parser with common arguments
base_parser = argparse.ArgumentParser(add_help=False)
base_parser.add_argument('--debug', action='store_true')
# Child parsers inherit from base
parser1 = argparse.ArgumentParser(parents=[base_parser])
parser1.add_argument('file')
parser2 = argparse.ArgumentParser(parents=[base_parser])
parser2.add_argument('--output')
Handling errors gracefully
import argparse
import sys
parser = argparse.ArgumentParser(exit_on_error=False)
parser.add_argument('file')
try:
args = parser.parse_args()
except argparse.ArgumentError as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)