I've added a dictionary that maps from names to function objects. This dictionary can also be used to limit the choices that the parser accepts.
import argparse
def create_parser():
parser = argparse.ArgumentParser(description='add method name')
parser.add_argument('--method_name', help='pass method name to be used',
choices=adict)
return parser
def foo():
return "I am here."
def bar():
return "I am not here."
adict = {'foo': foo, 'bar': bar} # map names to functions
def where_are_you(method_name):
fn = adict[method_name]
# could also use getattr
return fn()
def main():
args = create_parser().parse_args() # get the string
print(args.method_name) # debugging
return where_are_you(args.method_name)
if __name__ == '__main__':
print(main()) # show the return
testing:
0001:~/mypy$ python stack45667979.py -h
usage: stack45667979.py [-h] [--method_name {foo,bar}]
add method name
optional arguments:
-h, --help show this help message and exit
--method_name {foo,bar}
pass method name to be used
0001:~/mypy$ python stack45667979.py --method_name foo
foo
I am here.
0002:~/mypy$ python stack45667979.py --method_name baz
usage: stack45667979.py [-h] [--method_name {foo,bar}]
stack45667979.py: error: argument --method_name: invalid choice: 'baz' (choose from 'foo', 'bar')
The previous duplicate
Calling a function of a module from a string with the function's name
uses getattr
to perform a general search of the module namespace to match a string with a function. That could be used here, but may be too advanced for a beginner, and maybe too open ended even for advanced programmer. It is generally better to limit the choices you give your user to the set of known valid ones.
If this dictionary mapping is confusing I'd suggest a more obvious mapping
if args.method == 'foo':
foo()
elif args.method == 'bar':
bar()
else:
parser.error('bad method choice')