Python Argparse Argument Error Fix
In this tutorial, you'll learn about Python Argparse Argument Error Fix. We cover key concepts, practical examples, and best practices.
Argparse raises errors like "unrecognized arguments", "expected one argument", or "invalid int value" when the command-line input does not match the defined arguments. These occur when argument names are wrong, types mismatch, or required arguments are missing.
The Problem
python script.py --name John --age twenty
Error:
usage: script.py [-h] --name NAME --age AGE
script.py: error: argument --age: invalid int value: 'twenty'
Wrong Code
import argparse
# WRONG — no type validation, no required check
parser = argparse.ArgumentParser()
parser.add_argument('--name')
parser.add_argument('--age')
args = parser.parse_args()
print(f"Name: {args.name}, Age: {args.age}")
Right Code
import argparse
parser = argparse.ArgumentParser(description='Process user data')
parser.add_argument('--name', required=True, help='User name')
parser.add_argument('--age', type=int, required=True, help='User age')
parser.add_argument('--verbose', action='store_true', help='Enable verbose')
args = parser.parse_args()
print(f"Name: {args.name}, Age: {args.age}")
Expected output with correct input:
python script.py --name John --age 25
Name: John, Age: 25
Step-by-Step Fix
Step 1: Use type parameter for validation
parser.add_argument('--port', type=int, default=8080)
parser.add_argument('--rate', type=float, default=1.0)
Step 2: Add choices for restricted values
parser.add_argument('--mode', choices=['dev', 'prod', 'test'], default='dev')
Step 3: Handle missing arguments
# Use default values
parser.add_argument('--output', default='output.txt')
# Or make required
parser.add_argument('--input', required=True)
Step 4: Parse multiple values
parser.add_argument('--files', nargs='+', help='List of files')
# Usage: --files a.txt b.txt c.txt
parser.add_argument('--count', nargs='?', const=1, type=int)
# --count → 1 (const value)
# --count 5 → 5
# (not given) → None
Step 5: Handle positional arguments
parser.add_argument('input_file', help='Input file path')
parser.add_argument('output_file', nargs='?', default='output.txt')
Step 6: Custom validation function
def positive_int(value):
ivalue = int(value)
if ivalue <= 0:
raise argparse.ArgumentTypeError(f"{value} is not positive")
return ivalue
parser.add_argument('--count', type=positive_int)
Step 7: Handle subcommands
subparsers = parser.add_subparsers(dest='command')
parser_create = subparsers.add_parser('create')
parser_create.add_argument('--name', required=True)
parser_delete = subparsers.add_parser('delete')
parser_delete.add_argument('--id', type=int, required=True)
args = parser.parse_args()
Prevention Tips
- Always set
typefor numeric arguments - Use
choicesfor enum-like arguments - Set
required=Truefor mandatory arguments - Provide helpful
helptext for every argument - Test argument parsing with different input combinations
Common Mistakes with argparse error
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro