首页 > 解决方案 > python函数代码中的错误输出

问题描述

我有rootFile = root.json文件内容是

{
  "tests":[
    {
      "test":"test1",
      "url":"url1"
    },
    {
      "test":"test2",
      "url":"url2"
    },
    {
      "test":"test3",
      "url":"url3"
    }
  ]
}

我有 python 函数,我要给它运行字符串参数

def check(params):
    runId=time.strftime("%Y%m%d-%H%M%S")
        outputFile=Path(""+runId+".txt")
    with open (rootFile) as rj:
        data=json.load(rj)
    for param in params:
        for t in data['tests']:
            if t['test'] == param:
                urlToUse=t['url']
                testrun(param, urlToUse, runId)
            else:
                nonExistingTest="Test "+param+" Doesn't exist \n"
                if not outputFile.exists():
                    with open(outputFile,"a") as noSuchTest:
                        noSuchTest.write("Test "+param+" Doesn't exist \n")
                elif not nonExistingTest in open(outputFile).read():
                    with open(outputFile,"a") as noSuchTest:
                        noSuchTest.write("Test "+param+" Doesn't exist \n")
    with open(outputFile,"r") as pf:
        message=pf.read()
        slackResponse(message)

当我的参数是 root.json 文件中存在的“test1 test2 test3”时,我得到了这样的响应

Test test1 passed #this response comes from testrun() function
Test test1 Doesn't exist

Test test2 Doesn't exist
Test test2 passed  #this response comes from testrun() function

Test test3 Doesn't exist
Test test3 passed  #this response comes from testrun() function

但是当我给出不存在的参数时,输出是正确的。例如

Test test4 Doesn't exist
Test test5 Doesn't exist
Test test6 Doesn't exist
Test test7 Doesn't exist

无法理解为什么它实际存在时发送不存在

标签: pythonarraysjson

解决方案


您正在将通过函数调用传递的每个参数与tests从 json 文件加载的数组的每个项目进行比较,开始对等性的相应测试,并回显一条消息,说明这样的测试不存在。因为这个比较对于每个参数只会有一次肯定的结果,但会检查root.json每个参数指定的测试次数,输出中会有很多行表明特定参数不匹配中指定的特定测试root.json

一旦找到root.json当前参数正在寻址的条目,您将需要某种方法来退出循环。我建议将分配给testsin的数据结构root.json从数组更改为对象,将测试名称作为键,将它们的 url 作为值,或者以某种方式过滤与当前参数进行比较的可能测试列表。

考虑将内部的所有内容更改for param in params:为以下内容:

matching_tests = [t for t in data['tests'] if t['test'] == param]
if len(matching_tests) > 0:
    for t in matching_tests:
        urlToUse=t['url']
        testrun(param, urlToUse, runId)
else:
    nonExistingTest="Test "+param+" Doesn't exist \n"
    [...]

这样,表示没有与给定参数匹配的测试的消息最多只会回显一次。


推荐阅读