python - 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
无法理解为什么它实际存在时发送不存在
解决方案
您正在将通过函数调用传递的每个参数与tests
从 json 文件加载的数组的每个项目进行比较,开始对等性的相应测试,并回显一条消息,说明这样的测试不存在。因为这个比较对于每个参数只会有一次肯定的结果,但会检查root.json
每个参数指定的测试次数,输出中会有很多行表明特定参数不匹配中指定的特定测试root.json
。
一旦找到root.json
当前参数正在寻址的条目,您将需要某种方法来退出循环。我建议将分配给tests
in的数据结构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"
[...]
这样,表示没有与给定参数匹配的测试的消息最多只会回显一次。
推荐阅读
- swift - 如何在嵌套循环中访问变量?
- c++ - 使用 Excel VBA 中的 C++ dll 时出现“错误的 DLL 调用约定” - 如何解决?
- java - 自定义 JPasswordField 中的高 CPU 使用率
- mongodb - 使用 Mongoose 时的 MongoDB 弃用警告
- facebook-marketing-api - 消息“应用程序没有能力进行此 API 调用。” 在 API '/adcreative'
- java - maven 项目无法执行“maven-thrift-plugin”
- authentication - 主要的第一方移动应用程序如何确保其登录流程只能在其应用程序内完成?
- python - 如何用我自己的函数初始化 pytorch 中的权重?(cs231n PyTorch 笔记本)
- c - “删除事件”信号的回调函数传递了不正确的变量值
- angularjs - 单击链接时Angularjs ui-view路由不起作用