using argparse code example
Example 1: how to use argparse
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
Example 2: python argparse file argument
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file', type=argparse.FileType('r'))
args = parser.parse_args()
print(args.file.readlines())
Example 3: argparse python
# Generic parser function intialization in PYTHON
def create_parser(arguments):
"""Returns an instance of argparse.ArgumentParser"""
# your code here
parser = argparse.ArgumentParser(
description="Description of your code")
parser.add_argument("argument", help="mandatory or positional argument")
parser.add_argument("-o", "--optional",
help="Will take an optional argument after the flag")
namespace = parser.parse_args(arguments)
# Returns a namespace object with your arguments
return namespace
Example 4: 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":
...