calling function in argparse code example
Example 1: how to use argparse
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="what the program does")
parser.add_argument("arg1", help="advice on arg")
parser.add_argument("arg2", help="advice on arg")
parser.add_argument("argn", help="advice on arg")
args = parser.parse_args()
args.arg1, args.arg2 ... args.argn
Example 2: use argparse to call function and use argument in function
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'])
if args.help:
if args.function is None:
print parser.format_help()
sys.exit(1)
sub_args.append('--help')
function = "function1" if args.function is None else args.function
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":
...