How to handle invalid arguments with argparse in Python?


Argparse is a Python module used to create user-friendly command-line interfaces by defining program arguments, their types, default values, and help messages. The module can handle different argument types and allows creating subcommands with their own sets of arguments. Argparse generates a help message that displays available options and how to use them, and it raises an error if invalid arguments are entered. Overall, argparse simplifies the creation of robust command-line interfaces for Python programs.

Using try and except blocks

One way to handle invalid arguments with argparse is to use try and except blocks.

Example

In this code, we first import the argparse module and create an ArgumentParser object.

We add a command-line argument to the parser using the add_argument() method. In this case, we're defining an argument called --num that takes an integer value.

We then parse the command-line arguments using the parse_args() method.

Inside a try block, we attempt to square the value of args.num and store the result in a variable called result.

If the argument passed for --num is a valid integer, then the try block will execute successfully and the program will print the result.

However, if an invalid argument (such as a string or a floating point number) is passed for --num, then the try block will raise a TypeError exception. We catch this exception with an except block, which prints an error message indicating that 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.")

Assuming the code is in a file named my_script.py, and you want to square the number 4, you would open a terminal window and type:

~$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 compute the square of 4 (which is 16) and print the result:

Output

Result: 16

Using the choices argument

A second way to handle invalid arguments with argparse is to use the choices argument.

Example

In this code, we again create an ArgumentParser object and define a command-line argument called --color.

However, in this case, we use the choices argument to specify a list of valid choices for the --color argument. Any argument passed for --color that isn't in the list of valid choices will raise an error.

When the parse_args() method is called, argparse will automatically check whether the value of args.color is one of the valid choices. If it is, the program will print the chosen color. If not, argparse will raise an error indicating that the argument is invalid.

#my_script.py
import argparse
parser = argparse.ArgumentParser()

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

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

Assuming the code is in a file named my_script.py, and you want to choose the color ‘blue’, you would open a terminal window and type:

~$python my_script.py --color blue

This will run the script and pass blue as the --color argument. The script will then print the result as follows.

Output

Your chosen color is: blue

Using custom error messages

A third way to handle invalid arguments with argparse is to use custom error messages.

Example

In this code, we define a custom function called check_positive that takes a value as an argument and checks whether it's a positive integer. If the value is not a positive integer, the function raises an ArgumentTypeError exception with a custom error message.

We then define the ArgumentParser object and add an argument called --num, which uses the check_positive function to validate the input.

When the parse_args() method is called, argparse will automatically call the `

check_positive function to validate the input. If the input is a positive integer, the program will print the squared result. If not, argparse will raise an error with the custom error message we defined in the check_positive function.

#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)

Assuming the code is in a file named my_script.py, and you want to square the number 9, you would open a terminal window and type:

~$python my_script.py --num 9

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

Output

Result: 81

If the the argument to the script is say -9 like this

~$python my_script.py –num -9

It will show error like this

Output

my_script.py: error: argument --num: Value must be positive.

Using the nargs argument

The nargs argument in argparse can be used to specify the number of command-line arguments that are expected for a particular option. Here's an example of how to use it to handle invalid arguments:

Example

In this code, we create an ArgumentParser object and define an option called --numbers. We set the nargs argument to +, which means that the option expects one or more command-line arguments.

We then parse the command-line arguments using the parse_args() method.

If at least one integer value is passed for --numbers, the program will calculate the sum of the values and print the result. If no arguments are passed, the program will print a message indicating that at least one integer must be entered.

#my_script.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--numbers', nargs='+', type=int, help='Enter a list of 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.")

Assuming the code is in a file named my_script.py, and you want to enter two arguments 7 and 8, you would open a terminal window and type:

~$python my_script.py --numbers 7 8

This will run the script and pass the integer values 7 and 8 as the --numbers argument. The script will then compute the sum of 7 and 8 (which is 15) and print the result:

Output

Result: 15

If the argument to the script is say ‘’ (no argument) like this

~$python my_script.py –numbers 

It will show error like this

Output

my_script.py: error: argument --numbers: expected at least one argument

Conclusion

In summary, there are several ways to handle invalid arguments with argparse in Python, including using try-except blocks, the choices argument, custom error messages, the nargs argument, and subparsers. Choosing the appropriate method will depend on the specific requirements of your program and how you want to handle invalid inputs.

Updated on: 10-Aug-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements