在Python脚本中循环运行Bash命令

2024-09-28 05:26:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有我的这个脚本,它是用来修改我从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()

**

提前谢谢。在


Tags: 模块csv数据代码import脚本homeserial
1条回答
网友
1楼 · 发布于 2024-09-28 05:26:55

在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中的片段(this val[18:42])是从0索引的

相关问题 更多 >

    热门问题