在Python中使用组合
我使用Python的argparse获取用户输入,以从测试管理系统中选择数据,这些数据与所选状态、特定组、特定配置或三者的混合匹配 关于如何实现这三种选择的混合,我的脑子一直在绞尽脑汁。例如,如果用户希望检索具有特定状态的特定组中的测试,则代码将为在Python中使用组合,python,Python,我使用Python的argparse获取用户输入,以从测试管理系统中选择数据,这些数据与所选状态、特定组、特定配置或三者的混合匹配 关于如何实现这三种选择的混合,我的脑子一直在绞尽脑汁。例如,如果用户希望检索具有特定状态的特定组中的测试,则代码将为 if ( ((args.plan_section != None) and (test_data['name'] == args.plan_section)) and ((args.test_status != None) and (test_dat
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块。这似乎不合理——当我需要在将来的某个时候添加另一个参数(特定平台)时会发生什么
有人能在正确的方向上轻推一下吗。你不需要对照
无
进行检查。您可以直接比较:
if test_data['name'] == args.plan_section and \
test_data['test_status'] == args.test_status:
然而,这也将很快变得麻烦。尝试确保test\u data
-字典中的键与argparse
选项匹配如何?例如,test\u data['name']
必须是test\u data['plan\u section']
(因为您正在将name
与plan\u section
进行比较)
然后可以通过调用args=vars(args)
将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}
正如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\u调用(*args)
或类似方法。请参阅(和字典)。简化这一过程在很大程度上取决于如何调用测试管理api。