Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

What is argparse exit_on_error in Python?

Ayesha Naeem

The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors.

Explanation

The parse_arge() function of the ArgumentParser class parses arguments and the add_argument() function adds arguments to be accepted from the user.

When a user provides an invalid argument, the program exits and displays the error information. If the user wants to prevent this and catch the error manually, they can turn the exit_on_error feature off when creating the ArgumentParses object.

Examples

The following examples demonstrate how to use and disable the exit_on_error feature in the argparse module:

Example 1

The following program creates an ArgumentParser class, and by default, the exit_on_error feature is enabled.

An argument radius of type int is created; however, the user supplies a string instead of an integer, so the program throws an argument error, as seen here:

import math
import argparse

# create an ArgumentParser object
parser = argparse.ArgumentParser(description = 'Calculate radius of the circle')
# add arguments
parser.add_argument('-r','--radius', type = int, required = True, help='radius of the circle')
args = parser.parse_args('-r str'.split())
print(args)




                       

Example 2

The following program creates an ArgumentParser class and disables the exit_on_error feature.

An argument radius of type int is created; however, the user supplies a string instead of an integer, so the program throws an argument error.

The program catches the error through the try and except commands and displays a customized behavior specified by the user, as shown below:

import math
import argparse

# create an ArgumentParser object
parser = argparse.ArgumentParser(exit_on_error=False)
# add arguments
parser.add_argument('-r','--radius', type = int, required = True, help='radius of the circle')
try:
    args = parser.parse_args('-r str'.split())
    print(args)
except argparse.ArgumentError:
    print('Argument error caught')



                       

Output

Argument error caught

This feature is introduced in Python version 3.9.

RELATED TAGS

python

CONTRIBUTOR

Ayesha Naeem
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring