Python programs can accept input directly from the command line using the argparse module, part of the standard library. This module provides a robust and flexible way to define and parse commend-line options, arguments, and subcommends.
The core workflow involves creating an ArgumentParser object, defining expected arguments with add_argument(), and then parsing the actual command-line input with parse_args(). Each defined argument maps to an attribute on the resulting namespace object.
Positional Arguments with Variable Count
Use nargs='*' to collect zero or more positional arguments into a list:
import argparse
parser = argparse.ArgumentParser(description='Process multiple files')
parser.add_argument('files', metavar='FILE', nargs='*')
args = parser.parse_args()
print(args.files)
Running this script:
python script.py a.txt b.txt c.txt
outputs: ['a.txt', 'b.txt', 'c.txt'].
Boolean Flags
For simple on/off flags, use action='store_true':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--verbose', action='store_true',
help='Enable verbose output')
args = parser.parse_args()
print(args.verbose)
If -v or --verbose is provided, args.verbose becomes True; otherwise, it defaults to False.
Single-Value Options
To accept a single value for an option (the default behavior), use action='store' (which is implicit):
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output', dest='output_file',
help='Specify output file path')
args = parser.parse_args()
print(args.output_file)
Collectnig Multiple Values
Use action='append' to accumulate multiple occurrences of an option into a list:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--pattern', dest='patterns', action='append',
help='Add a search pattern')
args = parser.parse_args()
print(args.patterns)
Example usage:
python script.py -p "error" --pattern "warning"
Results in: ['error', 'warning'].
Restricted Choices and Defaults
Constrain acceptable values using the choices parameter and provide a fallback with default:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--mode', choices=['fast', 'slow'], default='slow',
help='Set processing speed')
args = parser.parse_args()
print(args.mode)
This ensures only 'fast' or 'slow' are accepted; if omitted, 'slow' is used.