由于性能原因,我试图创建一个串行读取缓冲区而不是使用readlines(),但是我无法按预期工作。 我从以下blog post获得了一些灵感。
我的readBuffer类定义如下所示:
def readBuffer(self):
try:
data = self.gpsdevice.read(1)
n = self.gpsdevice.inWaiting()
if n:
data = data + self.gpsdevice.read(n)
return data
except Exception, e:
print e
sys.exit(1)
我正在通过uart读取NMEA数据,我需要它逐行输出,但是当我执行以下测试时输出不是预期的
def test1():
newdata = ""
line = ""
while uart1.isOpen():
if newdata:
line = newdata
newdata = ""
line = line + uart1.readBuffer()
if "\r\n" in line:
print line
line = ""
test1()
输出:
$GNDTM,W84,,0.0000,N,0.0000,E,0.0000,W84*41
$GNGNS,,,,,,NN,00,,,,,,C*3C
$GNGBS,,,,,,,,,1,1*5F
$GNGBS,
,,,,,,,,2,1*5C
$GNRMC,,V,,,,,,,,,,N,C*22
$GNVTG,,T,,M,,N,,K,N*32
$GNZDA,,,,,00,00*56
$GNDTM,W84,,0.0000,N,0.0000,E,0.0000,W84*41
$GNGNS,,,,,,NN,00,,,,,,C*3C
$GNGBS,,,,,,,,,1,1*5F
$GNGBS,
,,,,,,,,2,1*5C
$GNRMC,,V,,,,,,,,,,N,C*22
$GNVTG,,T,,M,,N,,K,N*32
$GNZDA,,,,,00,00*56
$GNDTM,W84,,0.0000,N,0.0000,E,0.0000,W84*41
$GNGNS,,,,,,NN,00,,,,,,C*3C
$GNGBS,,,,,,,,,1,1*5F
$GNGBS,
,,,,,,,,2,1*5C
$GNRMC,,V,,,,,,,,,,N,C*22
$GNVTG,,T,,M,,N,,K,N*32
$GNZDA,,,,,00,00*56
$GNDTM,W84,,0.0000,N,0.0000,E,0.0000,W84*41
$GNGNS,,,,,,NN,00,,,,,,C*3C
$GNGBS,,,,,,,,,1,1*5F
$GNGBS,
,,,,,,,,2,1*5C
$GNRMC,,V,,,,,,,,,,N,C*22
$GNVTG,,T,,M,,N,,K,N*32
$GNZDA,,,,,00,00*56
我希望在每行的开头有句型($ GN ...),因为我需要能够将该行拆分为一个列表。这是因为我需要计算每种句子类型之间的出现次数。
我使用readline()完成了所有工作,但由于我要传递多行,我需要时机正确,我认为最好使用read()。
我在这里做错了什么?