我有我的这个脚本,它用于修改从GPS模块收集的一些数据。我运行了这段代码,但是它说有语法错误,我不明白为什么会有错误,通常我使用那个bash命令进行解析,不能在Python循环中使用它吗?

**

import serial
import struct
ser = serial.Serial("/dev/ttyUSB0", 4800, timeout = 1)
file = open("/home/pi/GPSWIFI.csv", "w")
file.write('\n')
for i in range(0,5):
       val = ser.readline();
       print >> file ,i,',',val
       cat /home/pi/GPSWIFI.csv | grep GPGGA | cut -c19-42 >GPSWIFIMODIFIED.csv
file.close()

**

提前致谢。

最佳答案

在python中运行bash命令可以使用os.system函数来完成,或者更推荐通过subprocess.Popen来完成。您可以在这里找到更多信息:

https://docs.python.org/2/library/subprocess.html#popen-constructor

如果改用python特定的实现,则更好,例如:

import serial
ser = serial.Serial("/dev/ttyUSB0", 4800, timeout = 1)
file = open("/home/pi/GPSWIFIMODIFIED.csv", "w")
file.write('\n')
for i in range(0,5):
       val = ser.readline();
       if val.find("GPGGA")==-1: continue
       print >> file ,i,',',val[18:42]
file.close()

请注意,python(此val[18:42])中的slice从0开始索引

关于python - 在Python脚本中循环运行Bash命令,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25245871/

10-11 23:23
查看更多