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.
Multiple ArugumentParser
objects often share the same arguments. It is redundant to specify the same arguments for every object. The argparse
module provides the option to create a parent parser class that contains the shared arguments. The parent parser class can then be supplied to the parents
argument of the ArgumentParser
object.
The following example demonstrates how to use shared arguments using a parent parser class.
The program creates a parent parser object parser
with an argument x
that is shared among parser2
and parser3
.
parser
is supplied to the parents
argument of the parser2
and parser3
objects. The parents
argument accepts a list of parent parser objects and adds the positional and optional arguments of the parent parser to the current object.
Notice that the add_help
feature of the parent parser is turned off because otherwise, the two help
options from the parent and child parsers will conflict and raise an error.
import mathimport argparse# create an ArgumentParser objectparser = argparse.ArgumentParser(add_help = False)# add argumentsparser.add_argument('-x', type = int, required = True, help='X')args = parser.parse_args('-x 10'.split())print(args)# create an ArgumentParser objectparser2 = argparse.ArgumentParser(parents = [parser])# add argumentsparser2.add_argument('-y', type = int, required = True, help='Y')args2 = parser2.parse_args('-x 10 -y 30'.split())print(args2)# create an ArgumentParser objectparser3 = argparse.ArgumentParser(parents = [parser])# add argumentsparser3.add_argument('-z', type = int, required = True, help='Z')args3 = parser3.parse_args('-x 10 -z 30'.split())print(args3)
Free Resources