在Python中使用组合

时间:2014-02-27 10:23:18

标签: python

我正在使用Python的argparse来获取用户输入,以便从测试管理系统中选择与所选状态,特定组,特定配置或三者混合的数据。

我很难将大脑包含在如何实现所有三种选择的混合物中。例如,如果用户想要检索具有特定状态的特定组中的测试,则代码将为

if ( ((args.plan_section != None) and (test_data['name'] == args.plan_section))
and ((args.test_status != None) and (test_data['test_status'] == args.test_status)) ):
    # call the test management system api

虽然这样编码就意味着为用户可以选择的每种可能组合编写if / then块。这似乎不合理 - 当我需要在将来某个时候添加另一个参数(特定平台)时会发生什么?

有人可以在正确的方向上轻推。

2 个答案:

答案 0 :(得分:0)

您无需检查None。你可以直接比较:

if test_data['name'] == args.plan_section and \
    test_data['test_status'] == args.test_status:

然而,这也将很快变得麻烦。如何确保test_data字典中的键与argparse选项匹配?例如,test_data['name']必须为test_data['plan_section'](因为您要将nameplan_section进行比较。)

然后,您可以通过调用args首先将args = vars(args)名称空间对象转换为字典来比较这些值。

以下是一个如何比较两个词典中的值的示例:

>>> args = {'foo': 1, 'bar': False}
>>> test_name = {'foo': 0, 'bar': False}
>>> for k, v in args.iteritems():
...     if test_name[k] != v:
...         print "key %s does not match. args: %s, test_name: %s" % (k, v, test_name[k])

Key foo does not match. args: 1, test_name: 0

或者,如果您只对匹配的项目感兴趣并根据这些项目进行api调用,则可以从字典中获取它们:

>>> result = {k: v for k, v in args.iteritems() if test_name[k] == v}
>>> result
{'bar': False}

答案 1 :(得分:0)

正如msvalkon所说,您可以取消对None的检查。正如我理解你的其余问题,你正在尝试为args中的每个有效参数执行一个操作。简单写作有什么问题:

if test_data['name'] == args.plan_section:
    # call the API to handle your first case

if test_data['test_status'] == args.test_status:
    # call the API to handle your second case

如果任何测试失败,Python将通过并继续处理剩余的案例。没有必要确保条件相互排斥。

如果您只想根据传递的参数组合进行看起来不同的单个API调用,那么答案取决于API调用的结构。如果您只想将argparse中的参数作为参数传递给API函数,则可以使用api_call(*args)或类似函数。请参阅 Python documentation on unpacking argument lists (和词典)。