Skip to main content

argparse.ArgumentParser

The ArgumentParser class is the main interface for command-line argument parsing in Python. It provides a simple way to define what arguments a program expects and automatically generates help messages and error handling.

📚 Basic Usage

import argparse

# Create the parser
parser = argparse.ArgumentParser(description='A simple example program')

# Add arguments
parser.add_argument('filename', help='Input file to process')
parser.add_argument('-v', '--verbose', action='store_true',
help='Enable verbose output')
parser.add_argument('-o', '--output', default='output.txt',
help='Output file name')

# Parse the arguments
args = parser.parse_args()

# Use the arguments
if args.verbose:
print(f"Processing {args.filename}")
print(f"Output will be saved to {args.output}")

Example from official documentation:

# Adapted from https://docs.python.org/3/library/argparse.html
parser = argparse.ArgumentParser(description='Process some integers.')
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)')

🔧 ArgumentParser Constructor

Class Signature

class ArgumentParser(prog=None, usage=None, description=None, epilog=None,
parents=[], formatter_class=HelpFormatter, prefix_chars='-',
fromfile_prefix_chars=None, argument_default=None,
conflict_handler='error', add_help=True, allow_abbrev=True,
exit_on_error=True)

Constructor Parameters

ParameterTypeDefaultDescription
progstrsys.argv[0]Name of the program
usagestrGeneratedCustom usage message
descriptionstrNoneText before argument help
epilogstrNoneText after argument help
parentslist[]List of ArgumentParser objects to inherit from
formatter_classclassHelpFormatterHelp message formatter
prefix_charsstr'-'Characters that prefix optional arguments
fromfile_prefix_charsstrNoneCharacters to read arguments from file
argument_defaultanyNoneDefault value for all arguments
conflict_handlerstr'error'How to handle conflicting options
add_helpboolTrueWhether to add -h/--help option
allow_abbrevboolTrueAllow abbreviation of long options
exit_on_errorboolTrueExit on error vs raise exception

Constructor Examples

# Basic parser
parser = argparse.ArgumentParser(description='My program')

# Custom program name and usage
parser = argparse.ArgumentParser(
prog='myapp',
usage='%(prog)s [options] file',
description='Process a file',
epilog='For more info, see the documentation'
)

# Custom formatter for help
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description='''
This is a multi-line description
that preserves formatting.

Indentation is preserved too.
'''
)

# Parser that doesn't exit on error (useful for testing)
parser = argparse.ArgumentParser(exit_on_error=False)

🛠️ Core Methods

Adding Arguments

add_argument(*name_or_flags, **kwargs)

Defines how a single command-line argument should be parsed.

Positional Arguments:

parser.add_argument('filename')  # Required positional argument
parser.add_argument('count', type=int) # With type conversion
parser.add_argument('files', nargs='+') # Multiple values

Optional Arguments:

parser.add_argument('-v', '--verbose', action='store_true')
parser.add_argument('-o', '--output', default='out.txt')
parser.add_argument('--count', type=int, required=True)

Key Parameters for add_argument()

ParameterDescriptionExample
actionHow to process the argument'store', 'store_true', 'append'
nargsNumber of arguments consumed'?', '*', '+', 2
constConstant value for some actionsUsed with store_const
defaultDefault value if not presentAny value
typeFunction to convert argumentint, float, open, custom function
choicesContainer of allowable values['a', 'b', 'c']
requiredWhether argument is required (optional args only)True, False
helpHelp message for the argumentString description
metavarName in usage messagesDisplay name for help
destAttribute name in result namespaceVariable name

Parsing Methods

parse_args(args=None, namespace=None)

Parse arguments and return a Namespace object.

# Parse sys.argv (default)
args = parser.parse_args()

# Parse custom argument list
args = parser.parse_args(['--verbose', 'input.txt'])

# Parse into existing namespace
existing = argparse.Namespace()
args = parser.parse_args(namespace=existing)

parse_known_args(args=None, namespace=None)

Parse known arguments, return tuple of (namespace, remaining_args).

args, unknown = parser.parse_known_args()
print(f"Known: {args}")
print(f"Unknown: {unknown}")

parse_intermixed_args(args=None, namespace=None)

Parse arguments allowing positionals and optionals to be intermixed.

# Normally: prog positional --optional value
# Intermixed allows: prog --optional value positional
args = parser.parse_intermixed_args()

Argument Groups

add_argument_group(title=None, description=None)

Create a logical group of arguments for better help organization.

# Create groups for better help organization
input_group = parser.add_argument_group('input options')
input_group.add_argument('--input-file', help='Input file path')
input_group.add_argument('--input-format', choices=['json', 'csv'])

output_group = parser.add_argument_group('output options')
output_group.add_argument('--output-file', help='Output file path')
output_group.add_argument('--output-format', choices=['json', 'csv'])

add_mutually_exclusive_group(required=False)

Create a group where only one argument can be specified.

group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--verbose', action='store_true')
group.add_argument('--quiet', action='store_true')
# User must specify either --verbose or --quiet, but not both

Subcommands

add_subparsers(**kwargs)

Create subcommands (like git commit, git push).

# Main parser
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='command', help='Available commands')

# Create subcommand
create_parser = subparsers.add_parser('create', help='Create a new item')
create_parser.add_argument('name', help='Name of the item')
create_parser.add_argument('--type', default='basic', help='Type of item')

delete_parser = subparsers.add_parser('delete', help='Delete an item')
delete_parser.add_argument('name', help='Name of the item to delete')

# Usage: prog create myitem --type advanced
# prog delete myitem

Help and Error Handling

Print complete help message.

parser.print_help()  # Print to stdout
with open('help.txt', 'w') as f:
parser.print_help(f) # Print to file

Print brief usage message.

parser.print_usage()

format_help()

Return help string without printing.

help_text = parser.format_help()

error(message)

Print error message and exit.

if not os.path.exists(args.input_file):
parser.error(f"Input file '{args.input_file}' does not exist")

📊 Complete Method Reference

Core Parser Methods

MethodDescriptionReturn TypeExample
add_argument()Add argument definitionNoneparser.add_argument('--verbose')
parse_args()Parse command lineNamespaceargs = parser.parse_args()
parse_known_args()Parse known argumentstupleargs, unknown = parser.parse_known_args()
parse_intermixed_args()Parse with mixed orderNamespaceargs = parser.parse_intermixed_args()

Grouping Methods

MethodDescriptionReturn Type
add_argument_group()Create argument groupArgumentGroup
add_mutually_exclusive_group()Create exclusive groupMutuallyExclusiveGroup
add_subparsers()Add subcommand support_SubParsersAction

Help and Information

MethodDescriptionReturn Type
print_help()Print help messageNone
print_usage()Print usage lineNone
format_help()Get help as stringstr
format_usage()Get usage as stringstr

Configuration and Control

MethodDescriptionReturn Type
set_defaults()Set default valuesNone
get_default()Get default for argumentany
error()Print error and exitNoReturn
exit()Exit with status codeNoReturn

💡 Advanced Usage Patterns

1. Custom Type Conversion

def positive_int(value):
"""Custom type that ensures positive integers."""
ivalue = int(value)
if ivalue <= 0:
raise argparse.ArgumentTypeError(f"{value} is not a positive integer")
return ivalue

parser.add_argument('--count', type=positive_int, help='Positive integer')

2. File Handling

# Using FileType for automatic file opening
parser.add_argument('--input', type=argparse.FileType('r'),
default='-', help='Input file (or stdin)')
parser.add_argument('--output', type=argparse.FileType('w'),
default='-', help='Output file (or stdout)')

args = parser.parse_args()
data = args.input.read() # File is already opened
args.output.write(processed_data)

3. Configuration File Integration

# Enable reading arguments from file
parser = argparse.ArgumentParser(fromfile_prefix_chars='@')

# Usage: python script.py @config.txt
# config.txt contains:
# --verbose
# --output
# result.txt
# input.txt

4. Argument Validation

def validate_range(value):
ivalue = int(value)
if not 1 <= ivalue <= 100:
raise argparse.ArgumentTypeError(f"Value {value} not in range 1-100")
return ivalue

parser.add_argument('--percent', type=validate_range,
help='Percentage value (1-100)')

5. Complex Subcommand Structure

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='command')

# Database commands
db_parser = subparsers.add_parser('db')
db_subparsers = db_parser.add_subparsers(dest='db_command')

create_parser = db_subparsers.add_parser('create')
create_parser.add_argument('--name', required=True)

migrate_parser = db_subparsers.add_parser('migrate')
migrate_parser.add_argument('--version', type=int)

# Usage: program.py db create --name mydb
# program.py db migrate --version 2

🚨 Common Pitfalls and Solutions

1. Conflicting Argument Names

# Problem: Both arguments use same destination
parser.add_argument('-f', dest='file')
parser.add_argument('--file', dest='file') # Conflict!

# Solution: Use consistent naming or different destinations
parser.add_argument('-f', '--file') # Both map to 'file'

2. Required Optional Arguments

# Required optional argument (contradictory but valid)
parser.add_argument('--config', required=True,
help='Configuration file (required)')

3. Boolean Flags with Values

# Don't do this for boolean flags
parser.add_argument('--verbose', type=bool) # Confusing

# Do this instead
parser.add_argument('--verbose', action='store_true')
parser.add_argument('--no-verbose', action='store_false')
  • Namespace Objects - Working with parsed results
  • Action Classes - Custom argument processing
  • FileType Class - File handling utilities
  • argparse Tutorial - Step-by-step guide
  • argparse API Reference - Complete documentation

📋 See Also

  • sys.argv - Raw command-line arguments
  • getopt - Alternative argument parsing (deprecated)
  • shlex - Shell-like argument splitting

ArgumentParser is the primary class for command-line argument parsing. Master this class to build robust command-line interfaces in Python.