如何创建异常代码(Arduino与python Tkinter的接口)

2024-07-05 14:44:28 发布

您现在位置:Python中文网/ 问答频道 /正文

这是来自Arduino的python接口:

运行python接口时,有时会出现以下错误:

raise SerialException('device reports readiness to read but returned no data (device disconnected or multiple access on port?)')SerialException: device reports readiness to read but returned no data (device disconnected or multiple access on port?)

这是代码的一部分:

import serial
import time
from Tkinter import *
root = Tk()
ser = serial.Serial("/dev/cu.usbmodem1411", 9600, timeout=1)
....
....
def do_update():
   ...
   allitems=ser.readline(4)
   x, y = allitems.split()
   ...
   root.after(1000, do_update)
   ...
do_update()
root.mainloop()

所以,我知道问题是当循环中没有数据传输时,如果发现这个错误消息,我如何告诉代码只显示最后一个值?在


Tags: tonoimportreaddatadevice错误update
1条回答
网友
1楼 · 发布于 2024-07-05 14:44:28

就像黑客狂指出的:

使用try/except/else/finally块捕获此异常。 要了解更多信息,请仔细查看documentation。在

你可以用像:


    def do_update():
        global ser
        try:
            """
            A try block runs until __ANY__ exception is raised
            """
            # do your stuff like reading / parsing data over here
            allitems=ser.readline(4)
            x, y = allitems.split()
        except serial.SerialException:
            """
            An except block is entered when a exception occured, can be parameterized by the type of exception. Using *except  as ex* you can access the details of the exceptions inside your exception Block.
            """
            # do whatever you want to do if __this specific__ exception occurs
            print("Serial Exception caught!")
        else:
            print("Different Exception caught!")
        finally:
            """
            A finally branch of a try/except/else/finally block is done always after an exception has occured.
            """
            # continue calling it again __always__
            root.after(1000, do_update)

相关问题 更多 >