Reputation: 733
I have a script with several functions:
def a():
pass
def b():
pass
def c():
pass
Which by design will be invoked depending on cmd line argument. I can create several if statements which will evaluate which function should run:
if args.function == "a":
a()
elif args.function == "b":
b()
elif args.function == "c":
c()
But is there a better way to do this?
Upvotes: 2
Views: 1983
Reputation: 1
Python has several built-in functions that we can utilize for instance Argparse, this method pretty common in python for command line programmable application. The basics:
import argparse
parser = argparse.ArgumentParser()
parser.parse_args()
By this method, you can have something like this:
$ python3 prog.py -v
verbosity turned on
$ python3 prog.py --help
usage: prog.py [-h] [-v]
optional arguments:
-h, --help show this help message and exit
-v, --verbose increase output verbosity
Upvotes: 0
Reputation: 3515
You make a dictionary as already pointed out, but how are you going to handle a bad input? I would create a default method and use the dict.get
method:
def fallback():
print('That command does not exist')
# add any code you want to be run for
# a bad input here...
functions = {
'a': a,
'b': b
}
Then call the function by retrieving it:
functions.get(args.function.lower(), fallback)()
Upvotes: 0
Reputation: 189915
Perhaps you are looking for a library like click
? It lets you easily add command-line subcommands with a decorator.
import click
@click.group()
def cli():
pass
@cli.command()
def a():
print("I am a")
@cli.command()
def b():
print("Je suis b")
if __name__ == '__main__':
cli()
Sample output:
bash$ ./ick.py --help
Usage: ick.py [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
a
b
bash$ ./ick.py a
I am a
Upvotes: 1
Reputation: 2546
Try using eval
eval(function_name_passed_as_argument + "()")
def a():
pass
def b():
pass
eval(args.function + "()")
This doesn't require the use of if-else
logic. Function name passed as argument will be executed directly.
Upvotes: 0
Reputation: 72855
You could make a dictionary like so
d = {"a" : a,
"b" : b}
and then dispatch
d[args.function]()
Upvotes: 3