Answers for "using argparse"

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
Posted by: Guest on December-09-2020
0

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":
    ...
Posted by: Guest on February-01-2021

Python Answers by Framework

Browse Popular Code Answers by Language