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: 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 accept only few options
...
parser.add_argument('--val',
choices=['a', 'b', 'c'],
help='Special testing value')
args = parser.parse_args(sys.argv[1:])
Example 4: 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":
...
Example 5: python argparser flags
parser.add_argument("-v", "--verbose", action="store_true",
help="verbose output")
Example 6: argparse python
def create_parser(arguments):
"""Returns an instance of argparse.ArgumentParser"""
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)
return namespace