python pass arguments argparse code example

Example 1: 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 2: 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":
    ...