【问题标题】:How to stop "serial.read(1)" after 5 seconds?如何在 5 秒后停止“serial.read(1)”?
【发布时间】:2020-01-09 11:01:15
【问题描述】:

我创建了一个通过串行端口与传感器通信的代码。我使用 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 multithreading


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回答!我会尝试并让您知道。
    【解决方案2】:

    我希望在读取线程本身中运行一个计时器,它会在 5 秒后加入线程。您可以查看此线程如何执行此操作:How to set a timeout to a thread

    【讨论】:

    • 感谢您的回答!我会尝试并让您知道。
    【解决方案3】:

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

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

    【讨论】:

    • 感谢您的回答!我会尝试并让您知道。
    猜你喜欢
    • 2019-10-17
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多