co89757
7/19/2017 - 7:22 PM

argparse module of Python usage example

argparse module of Python usage example

## Demonstrate how to use argparse in Python 

import argparse 
parser = argparse.ArgumentParser(
	description= "description of the command",
	epilog = "something optional you want to print at the end of summary"
	)

## ------ .add_argument() method -----
# keyword arguments for this method:
# - action = store (default) | store_const | append | append_const | store_true | store_false
# - nargs : expected number of arguments that should be consumed. N | ? | * | + 
# - const: a const value required by some action or nargs
# - default: default value for the arg
# - type: string(default) | int | float |...
# - choices:  similar to ValidateSet() attrib in powershell 
# - required: true|false
# - help
# - dest
# - metavar: a display name for the arg in usage printout 

parser.add_argument('-foo',action='store_const', const = 42)
# then you will have parser.parse_args(['-foo']).foo == 42 
parser.add_argument('--verbose','-v',action='store_true',help="turn on verbose logging")
# NOTE on use of nargs:
# '?'. One argument will be consumed from the command line if possible, and produced as a single item. 
# If no command-line argument is present, the value from default will be produced. 
# Note that for optional arguments, there is an additional case - the option string is present but not followed by a command-line argument. 
# In this case the value from const will be produced. 
parser.add_argument('--numbers',nargs='+', dest='numbers')
#type use
parser.add_argument('--max', type=int, help="max number to include in computation")
#choises
parser.add_argument('--sex', choices=['men','women'], required=True)

#---- start parsing args ----
args = parser.parse_args()