2

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?

**

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.

11
  • 1
    It says it is a syntax error ; File "GPSWIFII.py", line 10 cat /home/pi/GPSWIFI.csv | grep GPGGA | cut -c19-42 >GPSWIFIMODIFIED.csv Commented Aug 11, 2014 at 14:41
  • You can't just run bash commands directly like that. You need to import subprocess and set the parameter shell=True. You might find this tutorial helpful. Commented Aug 11, 2014 at 14:41
  • why are you writing a newline at the start? Commented Aug 11, 2014 at 15:00
  • Because I will change the format from write to append and all the data will be separated by one line in the same file. Commented Aug 11, 2014 at 15:04
  • and do you know about how I can make the date which I acquire from ntp can be printed in front of "i" in by adding a word in print >> file ,i,',',val ? Commented Aug 11, 2014 at 15:06

1 Answer 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:

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

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

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.