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

时间:2022-06-29 08:36:48

I have this script of mine and it is for modifying some data I gather from GPS module. I run this code but it says there is a syntax error and I couldn't understand why there is an error, normally I use that bash command for parsing, can't it be used in a Python loop?

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

**

* *

Thanks in advance.

提前谢谢。

1 个解决方案

#1


2  

running bash commands in python can be done using os.system function, or, more recommended, through subprocess.Popen. You can find more info here:

在python中运行bash命令可以使用操作系统。系统功能,或者更推荐通过子进程。popen。你可以在这里找到更多的信息:

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

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

It would be better if you used python-specific implementation instead, like this:

如果您使用特定于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()

note that slice in python (this val[18:42]) is indexed from 0

注意,在python中切片(这个val[18:42])从0索引。

#1


2  

running bash commands in python can be done using os.system function, or, more recommended, through subprocess.Popen. You can find more info here:

在python中运行bash命令可以使用操作系统。系统功能,或者更推荐通过子进程。popen。你可以在这里找到更多的信息:

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

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

It would be better if you used python-specific implementation instead, like this:

如果您使用特定于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()

note that slice in python (this val[18:42]) is indexed from 0

注意,在python中切片(这个val[18:42])从0索引。