Argument Parser in Python
Python argparse - Concise Notes
argparse
is a Python library for parsing command-line arguments. It provides a simple interface to define, process, and handle arguments.
Basic Usage
-
Setup
-
Adding Arguments
-
Positional Argument: Required, order matters
-
Optional Argument: Starts with
--
or-
, order doesnβt matter. -
Parsing Arguments
args = parser.parse_args()
print(args.filename) # Positional argument
print(args.verbose) # True/False (store_true)
print(args.number) # Integer value (default: 1)
Key Argument Settings
- Positional Arguments:
- No special prefix.
-
Example:
python script.py input.txt
-
Optional Arguments:
- Use
-
or--
. -
Example:
python script.py --verbose
-
Argument Types:
- Specify with
type
(e.g.,int
,float
,str
). -
Example:
-
Default Values:
- Use
default
. -
Example:
-
Boolean Flags:
- Use
action="store_true"
oraction="store_false"
. -
Example:
Example Usage
Script:
import argparse
parser = argparse.ArgumentParser(description="Demo script")
parser.add_argument("filename", help="Input file name")
parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbosity")
parser.add_argument("-n", "--number", type=int, default=10, help="Number of items")
args = parser.parse_args()
print(f"Filename: {args.filename}")
print(f"Verbose: {args.verbose}")
print(f"Number: {args.number}")
Run:
Output:
Common Methods
parser.add_argument()
: Define arguments.parser.parse_args()
: Parse command-line inputs.
Tips
- Use
help
for clear CLI documentation. - Default type is
str
if not specified. - Boolean flags (
store_true
) are ideal for toggles.
For most cases, this basic usage suffices!