Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

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

The user-supplied arguments and their values are verified by the parse_arg() function for errors. If the user supplies ambiguous arguments, invalid types, wrong names, or an incorrect number of arguments, the program exits, and the usage and error are displayed.

Examples

The following example demonstrates what some of the invalid argument types are.

Example 1

The following example provides an invalid value type for the argument -r:

import math
import argparse

# create an ArgumentParser object
parser = argparse.ArgumentParser()
# add arguments
parser.add_argument('-r', type = int)
parser.add_argument('--foo', type = int)
args = parser.parse_args('-r abc'.split())
print(args)

Example 2

The following example provides an invalid argument name:

import math
import argparse

# create an ArgumentParser object
parser = argparse.ArgumentParser()
# add arguments
parser.add_argument('-r', type = int)
parser.add_argument('--foo', type = int)
args = parser.parse_args('--bar'.split())
print(args)

Example 3

The following example provides an invalid number of arguments:

import math
import argparse

# create an ArgumentParser object
parser = argparse.ArgumentParser()
# add arguments
parser.add_argument('r', type = int)
parser.add_argument('foo', type = int)
args = parser.parse_args('10 8 3'.split())
print(args)

RELATED TAGS

python

CONTRIBUTOR

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

View all Courses

Keep Exploring