python - 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
解决方案
你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
推荐阅读
- c# - 使用带有 sas 令牌的 rest api 更新表存储实体说“方法不允许”
- javascript - 如何将数据从一个文件传输到另一个文件?
- android - 如何使用 CMAKE 切换到 c++_shared 或 c++_static?
- regex - sed - 替换行的一部分 - 引号中的单词
- r - 在 Roxygen 注释中包含 TeX
- c# - 如何使用带有 C# 的 ESC/POS 打印机打印指数数“m³”?
- asp.net-mvc - 如何将文本值传递给动作参数?
- c# - AppDomain.CurrentDomain.GetAssemblies() 没有给出项目参考
- android - 如何更新仅在 Recyclerview 适配器上单击的项目而不是最后一个可见的项目?
- c++ - 根据条件更新时 STM32F769 PWM 输出出现问题