Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to handle invalid arguments with argparse in Python?
Argparse is a Python module that helps you create easy-to-use command-line interfaces. When building these interfaces, it's important to handle invalid arguments properly to give clear feedback to users and prevent your program from crashing unexpectedly.
There are several ways to handle invalid arguments in argparse. You can catch errors using try-except blocks, restrict allowed options with choices, validate inputs with custom functions, or control the number of arguments using nargs. These methods make your command-line programs more reliable and user-friendly.
Using Try-Except Blocks
One simple method to handle invalid arguments is to put your argument parsing code inside a try-except block. This way, you can catch errors when argparse encounters invalid input ?
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--num", type=int, help="Enter an integer")
try:
args = parser.parse_args()
if args.num is not None:
result = args.num ** 2
print(f"Result: {result}")
else:
print("No number provided")
except SystemExit:
print("Invalid argument provided. Please check your input.")
When you run this with valid input, it calculates the square ?
Result: 16
Using the choices Parameter
The choices parameter restricts allowed values for a command-line argument. If an invalid value is provided, argparse automatically shows an error message ?
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--color", choices=["red", "green", "blue"],
help="Choose a color")
args = parser.parse_args()
if args.color:
print(f"Your chosen color is: {args.color}")
else:
print("No color selected")
With a valid choice like "blue", the output is ?
Your chosen color is: blue
An invalid choice like "yellow" would produce an error message explaining the valid options.
Custom Validation Functions
You can create custom validation functions to check if arguments meet specific conditions. If validation fails, raise an ArgumentTypeError with a helpful message ?
import argparse
def check_positive(value):
ivalue = int(value)
if ivalue <= 0:
raise argparse.ArgumentTypeError("Value must be positive")
return ivalue
parser = argparse.ArgumentParser()
parser.add_argument("--num", type=check_positive,
help="Enter a positive integer")
args = parser.parse_args()
if args.num:
result = args.num ** 2
print(f"Result: {result}")
With a positive number like 9, the output is ?
Result: 81
Using nargs for Argument Count Control
The nargs parameter controls how many values an argument should accept. This ensures users provide the correct number of inputs ?
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--numbers", nargs="+", type=int,
help="Enter one or more integers")
args = parser.parse_args()
if args.numbers:
result = sum(args.numbers)
print(f"Sum: {result}")
else:
print("No numbers provided")
With multiple integers like 7 and 8, the output is ?
Sum: 15
Comprehensive Error Handling
For robust applications, combine multiple validation techniques ?
import argparse
import sys
def validate_range(value):
ivalue = int(value)
if not (1 <= ivalue <= 100):
raise argparse.ArgumentTypeError("Value must be between 1 and 100")
return ivalue
parser = argparse.ArgumentParser(description="Demo comprehensive validation")
parser.add_argument("--level", type=validate_range,
help="Level between 1-100")
parser.add_argument("--mode", choices=["easy", "hard"],
default="easy", help="Game mode")
try:
args = parser.parse_args()
print(f"Level: {args.level}, Mode: {args.mode}")
except SystemExit as e:
if e.code != 0:
print("Please check your arguments and try again.")
sys.exit(1)
Common nargs Values
| nargs Value | Meaning | Example |
|---|---|---|
? |
0 or 1 argument | Optional single value |
* |
0 or more arguments | Any number of values |
+ |
1 or more arguments | At least one value required |
Number (e.g., 2) |
Exactly N arguments | Fixed number of values |
Conclusion
Proper error handling in argparse improves user experience and prevents crashes. Use choices for restricted options, custom functions for complex validation, and nargs for controlling argument count. Always provide clear error messages to help users correct their input.
