【问题标题】:How to create an exception code (Arduino interface with python Tkinter)如何创建异常代码(Arduino接口与python Tkinter)
【发布时间】:2015-11-03 06:57:51
【问题描述】:

这是来自 Arduino 的 python 接口:

在运行我的 python 界面时,有时我会收到此错误:

raise SerialException('设备报告准备读取但返回 没有数据(设备断开连接或多次访问 端口?)')SerialException:设备报告准备读取但返回 没有数据(设备断开连接或端口上的多个访问?)

这是代码的一部分:

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()

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

【问题讨论】:

  • 你可以使用try块来捕获异常

标签: python tkinter arduino pyserial


【解决方案1】:

就像 Hackaholic 指出的那样:

使用 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    • 2018-09-20
    • 2016-01-17
    • 2021-09-02
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    相关资源
    最近更新 更多