The argparse
module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors.
The parse_args()
function of the ArgumentParser
class parses arguments, and the add_argument()
function adds arguments to be accepted from the user.
The first argument for the add_argument()
function must be either a name or a series of flags. This tells the function to expect a positional argument or an optional argument like -f
.
The following example demonstrates how to use required command-line arguments.
The program program.py
takes two command-line arguments. The ArgumentParser
object parser
is created to add arguments and parse them.
foo
by supplying a name to the add_argument()
function.radius
, and leaves it as an optional argument. The add_argument()
function knows that the argument radius
is optional because the first argument for this function is a flag.import argparse#create an ArgumentParser objectparser = argparse.ArgumentParser(description = 'Calculate radius of the circle')#declare argumentsparser.add_argument('foo')parser.add_argument('-r','--radius', type = int, help='radius of the circle')args = parser.parse_args('bar -r 30'.split())print(args)
Free Resources