基于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
).
所以,应该这样做:
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屋!