基于argparse的调用函数 [英] Call function based on argparse
问题描述
我是python的新手,目前正在使用它. 我有一个脚本,对设备执行一些API调用.我想扩展功能并根据调用脚本时给出的参数调用不同的功能.
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.
当前,我有以下内容:
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()
我也有一个
def showtop20():
.....
和
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.
推荐答案
由于您似乎要根据给定的参数来运行一个且只有一个功能,因此建议您使用强制性位置参数./prog command
,而不是可选参数(./prog --command1
或./prog --command2
).
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()
这篇关于基于argparse的调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!