0

在我的 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())):
                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 Six.raise_from(e, None) File "", line 3, in raise_from File "C:\Users\pfra\ AppData\Local\Programs\P httplib_response = conn.getresponse())?

因为现在,我永远不知道到底出了什么问题。

非常感谢任何帮助。提前非常感谢。问候

4

1 回答 1

1

您将需要稍微修改您的except:.

看到这个:

>>> try:
...     a
... except:
...     print("Something went wrong!")
... 
Something went wrong!

并将其与:

>>> try:
...     a
... except NameError as e:
...     print(f"What went wrong is {e}")
... 
What went wrong is name 'a' is not defined

如果您不知道您的代码可能会抛出什么异常,您可以使用except Exception as e:. 但是,花时间了解您的代码可能抛出的异常是有意义的。

于 2020-11-10T15:34:18.333 回答