gpt4 book ai didi

python - 文档中令人困惑的 'readline' 警告

转载 作者:太空宇宙 更新时间:2023-11-03 15:18:32 24 4
gpt4 key购买 nike

我正在尝试实现串行通信,遵循 this advice .

基本上我会有一个单独的线程,它会阻塞,监听端口,当接收到完整的行时,将其推送到全局队列。

但是,文档中的这个警告让我感到困惑:

readlines() only works with a timeout

这是什么意思?我如何实现我的意图。我会讨厌必须

while True:
a = self.ser.read(1)
if a == '/n':
blqblq()
elif a == '/r'
b = self.ser.read(1)
if b == '/n':
nana()

最佳答案

readlines 必须有一个超时,否则它永远不会完成,因为没有办法检测串行数据流 (EOF) 的结束。

readline 在没有数据发送(或数据不包含换行符)时无限期阻塞,但您的应用程序也是如此。写这样的东西是完全可以的

def read(ser, queue):
while True:
queue.put(ser.readline())
threading.Thread(target=read, args=(ser, queue)).start()

或更现代的等价物

def read(ser, queue):
for line in ser:
queue.put(line)
threading.Thread(target=read, args=(ser, queue)).start()

但是,您应该知道阅读线程永远不会结束。因此,如果您的程序应该以非异常方式结束(即用户可以以某种方式退出它),您需要有一种机制来通知读取线程停止。为确保始终接收到此信号,您​​需要使用超时 - 否则,线程可能会在没有串行数据的情况下无限期阻塞。例如,这可能看起来像:

def read(ser, queue):
buf = b''
ser.timeout = 1 # 1 second. Modify according to latency requirements
while not should_stop.is_set():
buf += ser.readline()
if buf.endswith('\n'):
queue.put(line)
buf = b''
# else: Interrupted by timeout

should_stop = threading.Event()
threading.Thread(target=read, args=(ser, queue)).start()
# ... somewhat later
should_stop.set() # Reading thread will exit within the next second

关于python - 文档中令人困惑的 'readline' 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18739651/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com