我想用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删除/ n就是全部。
答案 0 :(得分: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,
答案 1 :(得分:1)
while True:
line = ser.readline()
if not line.strip():
continue
do_something_with(line)
答案 2 :(得分:0)
根据these tips,这应该做:
import serial
ser = serial.Serial("/dev/ttyACM0", 9600)
while True:
line = ser.readline()
if line:
print(line)
答案 3 :(得分: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()