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 adds value as an attribute dest
of the object. dest
identifies an argument.
dest
attribute of a positional argument equals the first argument given to the add_argument()
function.dest
attribute equals the first long option string without --
. Any subsequent -
in the long option string is converted to _
.dest
equals the first short option string without -
.For an argument
foo
, a short option can be of the type-f
, and a long option is of the--foo
type.
The following example demonstrates how the dest
keyword is attributed to arguments.
foobar
in the program below, is positional. dest
is equal to the first argument supplied to the add_argument()
function, as illustrated.radius_circle
, is optional. A long option string --radius
supplied to the add_argument()
function is used as dest
, as illustrated.-x
, is used for its dest
attribute.dest
attribute can be set manually by specifying the value of dest
in the arguments of add_argument()
.import mathimport argparse#create an ArgumentParser objectparser = argparse.ArgumentParser()#Add arguments#positional argumentparser.add_argument('foobar')#optional argument 1parser.add_argument('-r', '--radius-circle')# optional argument 2parser.add_argument('-x', '-y')parser.add_argument('-n','--newarg', dest = 'new' )obj = parser.parse_args('9 -r 1 -x 2 -n 5'.split())print(obj)
Free Resources