Using the very interesting answer provided here, I would like to be able to use argparse and execute multiple functions without having to define the arguments to each function. Otherwise the code is very overloaded or one has to multiply files to run different functions, which is not very practical either.
In the following example, the functions function1
and function2
have different arguments such as: function1(arg1: int, arg2: bool)
and function2(arg3: float, arg4: str)
# file test.py
import argparse
from file1 import function1
from file2 import function2
FUNCTION_MAP = {'function1' : function1, 'function2': function2}
parser = argparse.ArgumentParser()
parser.add_argument('command', choices=FUNCTION_MAP.keys())
# no specific argument to add here.
args = parser.parse_args()
func = FUNCTION_MAP[args.command]
func(**vars(args))
The following commands with --
arguments do not work.
python test.py "function1" --arg1=10 --arg2=True
python test.py "function2" --arg3=2.4 --arg4="a_file.csv"
command as python test.py "function1"
works but asks me the arguments of the function1
.
Thanks for your help.