简体   繁体   English

无法识别的\\ r \\ n行为

[英]Unidentified \r\n behavior

I am using PySerial 3.0.1 and Python3. 我正在使用PySerial 3.0.1和Python3。

Here is my following code. 这是我的以下代码。

port.send_break()
while (1):
    sys_reply = port.read(1)
    sys_reply_str = sys_reply.decode('cp437')
    print (sys_reply_str);
    if sys_reply_str == '>':
        break;

and the reply is something like: 回复是这样的:

...
V
e
r
s
i
o
n
...

>

Which is strange because if I wrote the code like this, 这很奇怪,因为如果我这样编写代码,

port.send_break()
while (1):
    sys_reply = port.read(100)
    sys_reply_str = sys_reply.decode('cp437')
    print (sys_reply_str);
    if sys_reply_str == '>':
        break;

The result I get is: 我得到的结果是:

...Version...

How is my first code example having a newline every input? 我的第一个代码示例每个输入如何换行? There is no "\\n" or "\\r" in the feedback from my sensor at all. 来自我的传感器的反馈中根本没有“ \\ n”或“ \\ r”。

In your first example, you read and print one byte in each loop. 在第一个示例中,您在每个循环中读取并打印一个字节。
The newline is added by each print . 每行print都会添加换行符。

In the second one, you read the whole sentence at once, as it is shorter than 100 bytes, and print it, so you have only one newline at the end. 在第二个句子中,您一次读取了整个句子,因为它短于100个字节,然后打印出来,因此末尾只有一个换行符。

You can change the default end of line (\\n) for print with the end parameter, as in: 您可以使用end参数更改print的默认行尾(\\ n),如下所示:

while (1):
    sys_reply = port.read(1)
    sys_reply_str = sys_reply.decode('cp437')
    print (sys_reply_str, end='');
    if sys_reply_str == '>':
        break;

To answer your comment: the common way to do it is to append each char to a list, and join them into a string at the end. 回答您的评论:常用的方法是将每个字符附加到列表中,并在最后将它们连接到字符串中。 The reason is that strings in Python are immutable, so adding a character at the end (as in s = s + c ) would involve the creation of a new s string at each addition. 原因是Python中的字符串是不可变的,因此在末尾添加一个字符(如s = s + c )将涉及在每次添加时创建一个新的s字符串。

received_chars = []
while (1):
    sys_reply = port.read(1)
    sys_reply_str = sys_reply.decode('cp437')
    received_chars.append(sys_reply_str)
    if sys_reply_str == '>':
        break;
received_string = ''.join(received_chars)
print(received_string)

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

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