2015-11-03 88 views
0

这是Arduino的一个Python接口:如何创建一个例外码(与Python Tkinter的Arduino的接口)

当运行我的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() 

所以,我理解的问题是,当没有数据传输上的循环,所以我怎么能告诉代码只显示最后一个值,如果它发现这个错误讯息?

+1

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

回答

0

就像Hackaholic指出:

使用try /除/其它/ 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)