使用argparse中的位置参数作为函数名 [英] Using positional arguments from argparse as function name
问题描述
我已经使用argparse设置了一个脚本,该脚本为我提供了以下命名空间:
I have set up a script with argparse that gives me the following NameSpace:
Namespace(action='list', input='all', target='domain')
我做了一些根据位置调用的函数,此刻我有了一种工作状态,可以用如下代码的代码来调用它们:
I have made a few functions which are called according to the positionals, and at the moment I have a working situation by calling them with blurbs of code like this one:
if args.action == 'list':
if len(sys.argv) == 2:
parser.print_help()
sys.exit(0)
elif args.target == 'domain':
domain_list()
elif args.target == 'forwarding':
forwarding_list()
elif args.target == 'transport':
transport_list()
elif args.target == 'user':
user_list()
else:
all_list()
我知道这可以做到,比这更好.但是由于我对Python的了解有限,我似乎无法弄清楚这一点.
I know this can be done way, way better than this; but with my limited knowledge of Python, I can't seem to figure this one out.
回顾:我想要的东西,如果可能的话(伪代码)
Recap: I want something like, if at all possible (pseudocode)
if args.action == 'add':
target = args.target
target_add()
其中target_add()
类似于domain_add()
.
提前谢谢!
推荐答案
听起来操作可能是list
或add
,而target
可能是domain
,forwarding
,transport
或user
.是的,如果您必须手动列出每个选项组合会执行的操作,则最终会得到很多if..then..else
代码.
It sounds like action could be list
or add
, while target
could be domain
, forwarding
, transport
, or user
. Yes, you would end up with a lot of if..then..else
code if you had to manually list what each combination of options would do.
这里是一种简化方法:
- 使用itertools.product生成所有可能的组合 选项.
- 使用白名单调度字典将选项映射到函数.键是2元组,例如
('domain','list')
或('transport','add')
.这些值是关联的功能对象.
- Use itertools.product to generate all the possible combinations of options.
- Use a whitelist dispatch dict to map options to functions. The keys are 2-tuples, such as
('domain','list')
, or('transport','add')
. The values are the associated function objects.
import itertools as IT
targets = 'domain forwarding transport user'.split()
actions = 'list add'.split()
dispatch = {key:globals()['%s_%s' % key] for key in IT.product(targets, actions)}
# This calls the function specified by (target, action).
# The `dict.get` method is used so that if the key is not in `dispatch`, the `all_list` function is called.
dispatch.get((args.target, args.action), all_list)()
这篇关于使用argparse中的位置参数作为函数名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!