简体   繁体   English

pyserial.readline()与python 2.7

[英]pyserial.readline() with python 2.7

I am using python 2.7.2 with pyserial 2.6. 我在pyserial 2.6中使用python 2.7.2。 What is the best way to use pyserial.readline() when talking to a device that has a character other than "\\n" for eol? 与具有“ \\ n”以外的其他字符的设备通话时,使用pyserial.readline()的最佳方法是什么? The pyserial doc points out that pyserial.readline() no longer takes an 'eol=' argument in python 2.6+, but recommends using io.TextIOWrapper as follows: ser = serial.serial_for_url('loop://', timeout=1) sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser)) pyserial文档指出pyserial.readline()在python 2.6+中不再采用'eol ='参数,但建议如下使用io.TextIOWrapper:ser = serial.serial_for_url('loop://',timeout = 1 )sio = io.TextIOWrapper(io.BufferedRWPair(ser,ser))

However the python io.BufferedRWPair doc specifically warns against that approach, saying "BufferedRWPair does not attempt to synchronize accesses to its underlying raw streams. You should not pass it the same object as reader and writer; use BufferedRandom instead." 但是python io.BufferedRWPair文档特别警告该方法,称“ BufferedRWPair不会尝试同步对其底层原始流的访问。您不应将其与读写器传递给同一对象;而应使用BufferedRandom。”

Could someone point to a working example of pyserial.readline() working with an eol other than 'eol'? 有人可以指出pyserial.readline()与“ eol”以外的其他eol一起工作的示例吗?

Thanks, Tom 谢谢汤姆

read() has a user-settable maximum size to the data it reads(in bits), if your data strings are a predictable length you could simply set that to capture a fixed-length string. read()具有读取的数据的用户可设置的最大大小(以位为单位),如果数据字符串是可预测的长度,则可以简单地将其设置为捕获固定长度的字符串。 it's sort of 'kentucky windage' in execution but so long as your data strings are consistent in size it won't bork. 这在执行中有点“肯塔基风波”,但只要您的数据字符串大小一致,就不会出错。

beyond that, your real option is to capture and write the data stream to another file and split out your entries manually/programatically. 除此之外,您真正的选择是捕获数据流并将其写入另一个文件,然后手动/以编程方式拆分您的条目。

for example, you could write your datastream to a .csv file, and adjust the delimiter variable to be your EoL character. 例如,您可以将数据流写入.csv文件,并将定界符变量调整为EoL字符。

Assume s is an open serial.serial object and the newline character is \\r. 假设s是一个打开的serial.serial对象,而换行符是\\ r。 Then this will read to end of line and return everything up to '\\r' as a string. 然后,它将读取到行尾,并将所有内容返回到字符串'\\ r'。

def read_value(encoded_command):
    s.write(encoded_command)
    temp = ''
    response = ''
    while '\r' not in response:
        response = s.read().decode()
        temp = temp + response
    return temp

And, BTW, I implemented the io.TextIOWrapper recommendation you talked about above and it 1)is much slower and 2)somehow makes the port close. 而且,顺便说一句,我实现了您在上面讨论的io.TextIOWrapper建议,它1)慢得多,2)以某种方式使端口关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM