What is argparse add_help in Python?

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_args() function of the ArgumentParser class parses arguments and the add_argument() function adds arguments to be accepted from the user.

The ArgumentParser object has a default argument -h or --help, that displays the parser’s help message.

It is often useful to disable this default argument by setting the add_help feature to False. For instance, consider that a parent parser with shared arguments is supplied to a child parser. The help arguments of the parent and child parsers will conflict if the help argument of the parent parser is not disabled.

Example

The following example demonstrates how the help feature of the parser works and how it can be disabled.

The following program creates two parsers. The first parser has the default help feature turned on, so it displays the help upon invoking the print_help() function.

The second parser disables the add_help feature, so it does not display the help.

import math
import argparse
# Parser with help
# create an ArgumentParser object
print("Parser with help")
parser = argparse.ArgumentParser()
# add arguments
parser.add_argument('-r', type = int, help= "this is r")
parser.add_argument('--foo', type = int)
print(parser.print_help())
# Parser without help
print("Parser without help")
parser2 = argparse.ArgumentParser(add_help = False)
# add arguments
parser2.add_argument('-r', type = int, help= "this is r")
parser2.add_argument('--foo', type = int)
print(parser2.print_help())
Copyright ©2024 Educative, Inc. All rights reserved