从命令行输出逐行处理

我有source中的Python代码,该代码可用于处理GPRMC格式。我修改了代码,其中数据来自"gpsd -d | awk -F ':' 'BEGIN{OFS=\":\"}{print $2}' | grep GPRMC",并且是这样的列表:

$GPRMC,220516,A,5133.82,N,00042.24,W,173.8,231.8,130694,004.2,W*70
$GPRMC,W*70

因此,当我启动它时,出现此错误:

data = ser.readline()
AttributeError: 'str' object has no attribute 'readline

下面是代码的一部分:

port = "gpsd -d | awk -F ':' 'BEGIN{OFS=\":\"}{print $2}' | grep GPRMC"

print("Receiving GPS data")
ser = port

find = False
while find == False:
    print("Waiting for GPRMC data")
    data = ser.readline()
if data[0:6] == "$GPRMC":
    parsingData = data.split(",")
    print(parsingData)
if parsingData[2] == "A":
    parseGPS(data)
    find = True

请帮助我解决此问题。 ps:我不是python编码器,只是几天我才开始使用这种语言,对不起我的英语不好

nijiaoshenmene 回答:从命令行输出逐行处理

从我读到的内容:您运行

gpsd -d | awk -F ':' 'BEGIN{OFS=\":\"}{print $2}' | grep GPRMC

在操作系统中,它返回类似于

的行

$GPRMC,220516,A,5133.82,N,00042.24,W,173.8,231.8,130694,004.2,W*70

这是我的解决方案。希望对您有所帮助:

from subprocess import Popen,PIPE
from re import search 

process = Popen("gpsd -d | awk -F ':' 'BEGIN{OFS=\":\"}{print $2}' | grep GPRMC",stdout=PIPE,shell=True,universal_newlines=True) 
while True: 
    line = str(process.stdout.readline())
    if not line: 
        break

    print("Receiving GPS data")
    find = False
    print(line)

    while find == False:  
        if search(r'$GPRMC',line):
            print("Waiting for GPRMC data")
            parsingData = line.strip().split(",")
            print(parsingData)
            if parsingData[2] == "A":
                parseGPS(data)
                find = True
,

这里有两个问题。

(1)ser是一个字符串。您需要在该字符串中运行命令,然后才能获取任何输出。

(2)一旦有输出,您就不会使用readline -这就是您从打开的文件中读取行的方式,并且您的输出也不会存储在文件中。

熟悉如何通过python运行OS命令。有很多方法可以做到这一点。如果您不知道从哪里开始,这里有个很棒的概述:https://stackoverflow.com/a/92395

本文链接:https://www.f2er.com/3089672.html

大家都在问