python - 如何在 5 秒后停止“serial.read(1)”?
问题描述
我创建了一个代码以通过串行端口与传感器进行通信。我使用带有串行库的 Python 3.7。
我的问题:“serial.read(1)”正在读取串口以查找一个字节(来自 FPGA 电子卡)。但是当没有什么要读的时候,程序就停在这条指令上,我不得不残忍地离开它。
我的目标:如果有要读的东西,程序会显示字节(带有“print()”)。但是如果没有什么要读取的,我希望程序在 5 秒后停止读取串口,而不是阻塞在这条指令上。
我正在考虑将线程用于“定时器功能”:第一个线程正在读取串行端口,而第二个线程正在等待 5 秒。5 秒后,第 2 个线程停止第 1 个线程。
def Timer():
class SerialLector(Thread):
""" Thread definition. """
def __init__(self):
Thread.__init__(self)
self.running = False # Thread is stopping.
def run(self):
""" Thread running program. """
self.running = True # Thread is looking at the serial port.
while self.running:
if ser.read(1):
print("There is something !",ser.read(1))
def stop(self):
self.running = False
# Creation of the thread
ThreadLector = SerialLector()
# Starting of the thread
ThreadLector.start()
# Stopping of the thread after 5 sec
time.sleep(5)
ThreadLector.stop()
ThreadLector.join()
print("There is nothing to read...")
结果:程序阻塞。我不知道如何在 5 秒后停止阅读!
解决方案
Python 标准库有一个signal
包,它为可能停止的函数提供超时功能:
https ://docs.python.org/3/library/signal.html
推荐阅读
- jupyter-notebook - 如何将文件存储在与 jupyter 不同的工作文件夹中
- ros - 在 libigl Viewer 上清除、移动、动画一个点?
- javascript - 我不知道打字稿中的返回类型
- python - 如何处理从 Python 中的用户输入创建字典的时间或内存限制错误?
- mongodb - MongoDB 存储和查询价格历史
- python - 如何获取它为1的列的ID
- ruby-on-rails - Rails 不生成 html.erb
- php - 从邮政编码中查找地址并在不重新加载页面的情况下编辑输入表单
- react-native - 如何将数据附加到状态数组?
- html - 如何使动画在 wordpress 中的特定页面上工作