The argparse
module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors.
required
is a parameter of the ArugmentParser
object’s function add_argument()
. By default, the arguments of type -f
or --foo
are optional and can be omitted. If a user is required to make an argument, they can set the keyword argument required
to True
.
The following example demonstrates how to use required command-line arguments.
The program program.py
takes a single command-line argument for the radius and calculates the area of the circle. The ArgumentParser
object parser
is created to add arguments and parse them.
The program adds an argument radius
and leaves it as an optional argument. If the user does not provide a value for the argument, the program will not throw an error and set the argument’s value as None
, as illustrated below:
import argparse#create an ArgumentParser objectparser = argparse.ArgumentParser(description = 'Calculate radius of the circle')#declare argumentsparser.add_argument('-r','--radius', type = int, help='radius of the circle')args = parser.parse_args()def main():print(args.radius)main()
None
As illustrated below, the compiler throws an error when the user sets an argument as required and does not provide a value for it.
import argparseparser = argparse.ArgumentParser(description = 'Calculate radius of the circle', prog = 'My program', usage = '%(prog)s [options]')parser.add_argument('-r','--radius', type = int, required = True, help='radius of the circle')args = parser.parse_args()def main():print(args.radius)main()
error: the following arguments are required: -r/--radius
Free Resources