首页 > 解决方案 > python 3.x - pyserial - 堆栈溢出致命错误

问题描述

我写了一个继承自 serial.Serial 对象的对象并添加了一些方法。在无限循环中,程序从串行连接中获取信息。当有人关闭另一侧的 Divice 时,SerialException 会通知用户出现问题并再次调用该函数。在大约 300 个错误之后,我得到一个堆栈溢出致命错误。

def endless():
 try:
  with serialObjectDerivedFromserial.Serial("/dev/tty/bsp") as bsp:
  #doing somthing
 except serial.SerialException:
  #notify not connected
  time.sleep(10)
  endless()
 except:
  #notify error

标签: pythonfatal-errorpyserial

解决方案


endless自己打电话。虽然它不是被禁止的(它是递归的基础),但每次调用都会消耗一点堆栈。因此,在多次调用后出现堆栈溢出也就不足为奇了。正确的方法是将递归改为迭代处理:

def endless():
  while True:
     try:
      with serialObjectDerivedFromserial.Serial("/dev/tty/bsp") as bsp:
      #doing somthing
     except serial.SerialException:
      #notify not connected
      time.sleep(10)
      continue               # keep on looping on SerialException
     except:
      #notify error
     break                   # exit loop on any other case

推荐阅读