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 is 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 and error messages, or control the number of arguments using nargs. Using these methods makes your command-line programs more reliable and user-friendly.

Using try and except Blocks

One simple method to handle invalid arguments is to put your argument code inside a try-except block. This way, you can catch errors when the argument values are not of the type you expect.

Example

In this example, we define an argument --num that expects an integer. We then try to square the value and catch a TypeError if the argument is invalid -

#my_script.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--num", type=int, help="Enter an integer")

args = parser.parse_args()

try:
   result = args.num ** 2
   print("Result:", result)
except TypeError:
   print("Invalid argument. Please enter an integer.")

The code above is saved in a file named my_script.py. To run it with the argument 4, open the command prompt and type the following -

python my_script.py --num 4

This will run the script and pass the integer value 4 as the --num argument. The script will then calculate the square of 4 (which is 16) and print the result -

Result: 16

If a non-integer is passed, the except block will handle the error and print a message as shown below -

python my_script.py -numbers 

usage: my_script.py [-h] [--num NUM]
my_script.py: error: unrecognized arguments: -numbers

Using the "choices" Argument

The choices argument is used to limit the allowed values for a command-line argument. If you enter a value that is not in the list of choices, argparse will automatically show an error message.

Example

In this example, we define an argument --color that only accepts "red", "green", or "blue". If the you provide a valid color, the script prints the chosen color -

# my_script.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--color", choices=["red", "green", "blue"], help="Choose a color")

args = parser.parse_args()
print("Your chosen color is:", args.color)

The code above is saved in a file named my_script.py. To run it with a valid color argument like blue, open the command prompt and type the following -

python my_script.py --color blue

This will run the script and pass the string "blue" as the --color argument. The script will then print the selected color as shown below -

Your chosen color is: blue

If you pass an invalid color, argparse will automatically handle the error and print a message as shown below -

python my_script.py --color yellow

usage: my_script.py [-h] [--color {red,green,blue}]
my_script.py: error: argument --color: invalid choice: 'yellow' (choose from 'red', 'green', 'blue')

Custom Validation with Error Messages

You can create your own function to check whether an argument meets certain conditions. If it doesn't, you can raise an error with a custom message to help the user understand the problem.

Example

In this example, we define a function check_positive that checks if the given number is positive. If the number is not positive, it raises an error with a custom message -

# my_script.py
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()

result = args.num ** 2
print("Result:", result)

The code above is saved in a file named my_script.py. To run it with a valid positive number like 9, open the command prompt and type the following -

python my_script.py --num 9

This will run the script and pass the integer 9 as the --num argument. The script will then calculate the square of 9 (which is 81) and print the result -

Result: 81

If a negative number is passed, the custom validation function will raise an error and print the following message -

python my_script.py --num -9

usage: my_script.py [-h] [--num NUM]
my_script.py: error: argument --num: Value must be positive.

Using the "nargs" Argument

The nargs argument is used to define how many command-line inputs an argument should accept. It helps to ensure that the user provides the correct number of values.

Example

In this example, we define an argument --numbers that accepts one or more integers. The script then calculates the sum of these numbers -

# my_script.py
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 is not None:
   result = sum(args.numbers)
   print("Result:", result)
else:
   print("Please enter at least one integer.")

To run it with multiple integers like 7 and 8, open the command prompt and type the following -

python my_script.py --numbers 7 8

This will run the script and pass the integers 7 and 8 as values to the --numbers argument. The script will then calculate the sum and print the result -

Result: 15

If no value is provided after --numbers, argparse will show an error message like the one below -

python my_script.py --numbers

usage: my_script.py [-h] [--numbers NUMBERS [NUMBERS ...]]
my_script.py: error: argument --numbers: expected at least one argument
Updated on: 2025-06-02T17:29:49+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements