gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 12:15:52 25 4
gpt4 key购买 nike

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

**

提前致谢。

最佳答案

可以使用 os.system 函数在 python 中运行 bash 命令,或者更推荐通过 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])是从 0 开始索引的

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com