5秒后如何停止"serial.read(1)"?



我创建了一个代码,通过串行端口与传感器通信。我使用带有串行库的Python 3.7。

我的问题:"serial.read(1("正在读取串行端口以查找一个字节(来自FPGA电子卡(。但是当没有什么可读的时,程序会停止在这个指令上,我被迫残酷地离开它。

我的目标:如果有东西要读,程序会显示字节(带有"print(("(。但是如果没有什么可读取的,我希望程序在 5 秒后停止读取串行端口,而不是阻止此指令。

我正在考虑将线程用于"计时器功能":第一个线程正在读取串行端口,而第二个线程正在等待 5 秒。5 秒后,第二个线程停止第一个线程。

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

我更愿意在读取线程本身中运行一个计时器,它将在 5 秒后加入线程。你可以检查这个线程如何做到这一点:如何设置线程的超时

最简单的解决方案是将线程作为守护程序启动并等待 5 秒以使其产生任何内容。之后,只需结束程序即可。然后 Python 将自行终止线程。

更优雅的解决方案将使用类似select()的东西,它可以等待多个文件描述符进入它们可以提供或接收数据的状态,并且还有超时。

最新更新