2015-11-03 90 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)