import argparse
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-n", "--name", required=True, help="name of the user")
args = vars(ap.parse_args())
# display a friendly message to the user
print("Hi there {}, it's nice to meet you!".format(args["name"]))
import argparse
if __name__ == "__main__":
#add a description
parser = argparse.ArgumentParser(description="what the program does")
#add the arguments
parser.add_argument("arg1", help="advice on arg")
parser.add_argument("arg2", help="advice on arg")
# .
# .
# .
parser.add_argument("argn", help="advice on arg")
#this allows you to access the arguments via the object args
args = parser.parse_args()
#how to use the arguments
args.arg1, args.arg2 ... args.argn
# importing required modules
import argparse
# create a parser object
parser = argparse.ArgumentParser(description = "An addition program")
# add argument
parser.add_argument("add", nargs = '*', metavar = "num", type = int,
help = "All the numbers separated by spaces will be added.")
# parse the arguments from standard input
args = parser.parse_args()
# check if add argument has any input data.
# If it has, then print sum of the given numbers
if len(args.add) != 0:
print(sum(args.add))
use argparse to call function and use argument in function
# Parse the subcommand argument first
parser = ArgumentParser(add_help=False)
parser.add_argument("function",
nargs="?",
choices=['function1', 'function2', 'function2'],
)
parser.add_argument('--help', action='store_true')
args, sub_args = parser.parse_known_args(['--help'])
# Manually handle help
if args.help:
# If no subcommand was specified, give general help
if args.function is None:
print parser.format_help()
sys.exit(1)
# Otherwise pass the help option on to the subcommand
sub_args.append('--help')
# Manually handle the default for "function"
function = "function1" if args.function is None else args.function
# Parse the remaining args as per the selected subcommand
parser = ArgumentParser(prog="%s %s" % (os.path.basename(sys.argv[0]), function))
if function == "function1":
parser.add_argument('-a','--a')
parser.add_argument('-b','--b')
parser.add_argument('-c','--c')
args = parser.parse_args(sub_args)
function1(args.a, args.b, args.c)
elif function == "function2":
...
elif function == "function3":
...