2

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?

1
  • Maybe you can do it as in the example docs.python.org/3.3/library/argparse.html#example. They use args.accumulate and this calls the function that is written in accumulate (i.e. sum or max). I think it should also work if you pass "a", "b" or "c" in accumulate. Commented Sep 28, 2020 at 10:29

5 Answers 5

3

You could make a dictionary like so

d = {"a" : a,
     "b" : b}

and then dispatch

d[args.function]()
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

Comments

0

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)()

Comments

0

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

1 Comment

You don't describe how it can help. I see output, but no idea what is under the hood when call '-v' option.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.