首页 > 解决方案 > 如何在 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 秒后停止阅读!

标签: pythonmultithreading

解决方案


Python 标准库有一个signal包,它为可能停止的函数提供超时功能: https ://docs.python.org/3/library/signal.html


推荐阅读