2

我想用 python 读取串口,用 readline 打印结果,但是我在所有结果行之间都得到了空行。你能告诉我如何删除所有空行吗?

我的代码:

#!/usr/bin/python

import serial
import time
import sys

ser = serial.Serial("/dev/ttyACM0", 9600)

print ser.readline()
print ser.readline()
print ser.readline()
print ser.readline()
print ser.readline()

我从后面尝试了几个答案,但仍然有空行。我的 txt 文件如下所示:

T:  59.30%  22.20 8% 11% N 

T:  59.80%  22.20 8% 11% N 

T:  59.80%  22.20 8% 11% N 

T:  59.80%  22.20 8% 11% N 

但我需要像这样的文件:

T:  59.30%  22.20 8% 11% N 
T:  59.80%  22.20 8% 11% N 
T:  59.80%  22.20 8% 11% N 
T:  59.80%  22.20 8% 11% N     

编辑:

找到解决该问题的方法:

    line = ser.readline().decode('utf-8')[:-2]

它现在工作正常。这 -2 delete /n 就是这样。

4

4 回答 4

3

任何一个:

import serial

with serial.Serial("/dev/ttyACM0", 9600) as ser:
    for line in ser:
        print line.rstrip('\n')

或者

import serial

with serial.Serial("/dev/ttyACM0", 9600) as ser:
    for line in ser:
        print line,
于 2013-05-12T17:13:18.437 回答
2
while True:
    line = ser.readline()
    if not line.strip():
        continue
    do_something_with(line)
于 2013-05-12T16:34:38.137 回答
0

根据这些提示,应该这样做:

import serial

ser = serial.Serial("/dev/ttyACM0", 9600)

while True:
    line = ser.readline()
    if line:
        print(line)
于 2013-05-12T16:42:48.433 回答
0
import serial
ser = serial.Serial('COM11', 115200, timeout = 0.01)
print("Starting up")
while True:
    try:
        line = ser.readline().decode('ascii').strip()
        if line:
            print (line)
    except:
        pass
    ser.flush()
于 2020-01-27T13:40:20.703 回答