I have a file called functions.py with several functions (func1, func2, func3.. ) I would like to write a parser that allows me to run these functions on a terminal/cluster in this way:
python parser.py -function func1 -inputf1_1 10 inputf1_2 20
and I could also do
python parser.py -function func2 -inputf2 'abc'
I know how to do this with different parser files (parser_func1.py, parser_func2.py) but I would prefer to have only one parser.py file.
This is how my code looks at the moment:
import argparse
def func1(x,y):
print (x*y)
def func2(text):
print (text)
ap = argparse.ArgumentParser()
FUNCTION_MAP = {'func1' : func1,
'func2' : func2}
# create the top-level parser
parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('command', choices=FUNCTION_MAP.keys(), help='choose function to run')
subparsers = parser.add_subparsers(help='sub-command help')
# create the parser for the "a" command
parser_a = subparsers.add_parser('func1', help='func1 help')
parser_a.add_argument("-x", "--x", required=True, help="number 1")
parser_a.add_argument("-y", "--y", required=True, help="number 2")
# create the parser for the "b" command
parser_b = subparsers.add_parser('func2', help='func2 help')
parser_b.add_argument("-text", "--text", required=True, help="text you want to print")
args = parser.parse_args()
func = FUNCTION_MAP[args.command]
#I don't know how to put the correct inputs inside the func()
func()
When I now run:
python functions.py func1 -x 10 -y 2
I get this error: usage: PROG [-h] {func1,func2} {func1,func2} ... PROG: error: invalid choice: '2' (choose from 'func1', 'func2')
I've read these but still could not figure out how to do it:
https://docs.python.org/3/library/argparse.html#module-argparse
Call function based on argparse
How to use argparse subparsers correctly?
Thank you!