Python 3.x 在Python中使用try和except时如何仍然显示错误消息
在我的Python代码中,我有一个带有“try”和“except”语句的函数:Python 3.x 在Python中使用try和except时如何仍然显示错误消息,python-3.x,error-handling,try-except,traceback,error-messaging,Python 3.x,Error Handling,Try Except,Traceback,Error Messaging,在我的Python代码中,我有一个带有“try”和“except”语句的函数: for x in range (int(firstSocketEntry.get()), int(lastSocketEntry.get())+1): # Test will be done according to the range of the sockets for attempt in range (int(attemptEntry.get())):
for x in range (int(firstSocketEntry.get()), int(lastSocketEntry.get())+1): # Test will be done according to the range of the sockets
for attempt in range (int(attemptEntry.get())):
try:
print('Attempt: ' + str(attempt+1))
print('DUT: ' + str(x))
time.sleep(1)
client = HTTPClient('http://' + ipEntry.get() + port)
response = client.send(Request('test_is_alive', x), timeout=httpTimeOutEntry.get())
# response = request("http://" + ipEntry.get() + port, "test_is_alive", x)
time.sleep(1)
print(response.text)
print(response.data.result)
answer = response.data.result
logFile.write(time.strftime("%Y_%m_%d-%H_%M_%S\t\t") + str(x) + "\t\t" + str(answer) + "\t\t" + str(readVoltage()) + "\t\t" + str(readCurrent()) + "\n")
except:
print("Something went wrong!")
executeFunctionX()
else:
if (response.data.result==False):
print("\nAttempt " + str(attempt + 1) + " failed!")
else:
break
else:
print('\nAll attempts failed!')
如果现在“try”语句中出现错误,代码将继续执行“except”语句,这是目标。
我如何仍能获得错误消息(即:
回溯(最近一次呼叫最后一次):
文件“C:\Users\pfra\AppData\Local\Programs\P
六、从(e,无)中提高
文件“”,第3行,从
文件“C:\Users\pfra\AppData\Local\Programs\P
httplib_response=conn.getresponse())
因为现在,我不知道到底出了什么问题
非常感谢您的帮助。先谢谢你。
关于您需要稍微修改您的
,除了:
见此:
>>试试:
... A.
... 除:
... 打印(“出错了!”)
...
出了点问题!
并将其与:
>>试试:
... A.
... 除名称错误为e外:
... 打印(f“出错的是{e}”)
...
问题是没有定义名称“a”
如果您不知道代码可能抛出什么异常,您可以使用exception as e:
。然而,花时间了解代码可能抛出的异常是有意义的