【问题标题】:wrong output in python function codepython函数代码中的错误输出
【发布时间】:2019-01-12 08:33:20
【问题描述】:

我有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

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

【问题讨论】:

    标签: python arrays json


    【解决方案1】:

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

    一旦找到当前参数所寻址的root.json 条目,您将需要某种方法来退出循环。我建议将分配给root.jsontests 的数据结构从数组更改为对象,将测试名称作为键,将它们的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"
        [...]
    

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

    【讨论】:

      猜你喜欢
      • 2016-06-27
      • 2020-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-29
      相关资源
      最近更新 更多