Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function based on argparse

I'm new to python and currently playing with it. I have a script which does some API Calls to an appliance. I would like to extend the functionality and call different functions based on the arguments given when calling the script.

Currently I have the following:

parser = argparse.ArgumentParser() parser.add_argument("--showtop20", help="list top 20 by app",                     action="store_true") parser.add_argument("--listapps", help="list all available apps",                     action="store_true") args = parser.parse_args() 

I also have a

def showtop20():     ..... 

and

def listapps(): .... 

How can I call the function (and only this) based on the argument given? I don't want to run

if args.showtop20:    #code here  if args.listapps:    #code here 

as I want to move the different functions to a module later on keeping the main executable file clean and tidy.

like image 504
f0rd42 Avatar asked Dec 17 '14 15:12

f0rd42


People also ask

What is Argparse ArgumentParser ()?

The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors. The parse_args() function of the ArgumentParser class parses arguments and adds value as an attribute dest of the object.

What is Metavar in Argparse Python?

Metavar: It provides a different name for optional argument in help messages.


1 Answers

Since it seems like you want to run one, and only one, function depending on the arguments given, I would suggest you use a mandatory positional argument ./prog command, instead of optional arguments (./prog --command1 or ./prog --command2).

so, something like this should do it:

FUNCTION_MAP = {'top20' : my_top20_func,                 'listapps' : my_listapps_func }  parser.add_argument('command', choices=FUNCTION_MAP.keys())  args = parser.parse_args()  func = FUNCTION_MAP[args.command] func() 
like image 50
Hannes Ovrén Avatar answered Oct 22 '22 22:10

Hannes Ovrén