pySerial 截断文件中的文本

pySerial cuts off text in file

我想通过串口打印出我Android上的一个文件的内容,但它只截掉了一半。

我的代码如下所示:

ser = Serial('/dev/ttyUSB0', 115200, timeout=0)
ser.write(' cat /sdcard/dump.xml \r\n')
sleep(5)
while ser.inWaiting():
    print ser.readline()
ser.close()

Cat 在我的串行端口终端内工作没有任何问题,因此必须使用串行 class 进行一些设置。它有一些最大限制吗?我试着用它的变量玩了一下,但似乎找不到任何有用的东西。

问题好像是inWaiting()返回false,导致读取停止。也就是说,如果你循环得足够快,就不会有任何数据 "in waiting" (因为你刚刚读取并循环)。

另请注意,没有超时 (=0) 的 readline() 将阻塞,直到它看到换行符,这意味着您可能会陷入循环。

最好将超时增加到例如一秒钟然后做一个相当大的 read() 附加到一个字符串(或列表)。缓冲区用完后就停止阅读,对结果做任何想做的事。也就是说,如果无法知道您何时收到所有东西。

ser = Serial('/dev/ttyUSB0', 115200, timeout=1) # NB! One second timeout here!
ser.flushInput() # Might be a good idea?
ser.flushOutput()
ser.write(' cat /sdcard/dump.xml \r\n')
sleep(5) # I really don't think you need to sleep here.

rx_buf = [ser.read(1024)] # Try reading a large chunk. It will read up to 1024 bytes, or timeout and continue.
while True: # Loop to read remaining data, to the end of the rx buffer.
    pending = ser.inWaiting()
    if pending:
        rx_buf.append(ser.read(pending)) # Read pending data, appending to the list.
        # You'll read pending number of bytes, or until the timeout.
    else:
        break

rx_data = ''.join(rx_buf) # Make a string of your buffered chunks.

免责声明:我没有 Python 带有可用串行端口的解释器,所以这超出了我的考虑范围。