USB GPS Receiver

Python gps / gpsd KeyError

I have been adding GPS logging to my Bicycle Dashcam. All of the example Python code (eg: I’ve found online throws this error after about a minute:

Exception has occurred: KeyError
File "", line 12, in
while 0 ==
KeyError: 'el'

I’m not sure if this is a problem unique to my GPS receiver, but it regularly sends data that is not “class”:”TPV” (eg: “class”:”SKY”) – TPV is the data with coordinates, and whenever that happens, all the sample code throws a KeyError.

I’ve found the easiest way to fix this is to add a TRY/EXCEPT inside the forever loop, catch the KeyError expection, and PASS. Here is an adaptation of code I found on Stackoverflow that solves the problem – I’ve submitted it as an improvement, hopefully they accept my edits!

import threading
import time
from gps import *
from datetime import datetime

class GpsPoller(threading.Thread):

   def __init__(self):
       self.session = gps(mode=WATCH_ENABLE)
       self.current_value = None

   def get_current_value(self):
       return self.current_value

   def run(self):
        while True: #moved the try INTO the forever loop, so pass from the except resumes collecting data
                self.current_value =
                time.sleep(0.2) # tune this, you might not get values that quickly
            except KeyError as e: #catch the KerError, and return to the forever loop
            except StopIteration:

#if __name__ == '__main__':

gpsp = GpsPoller()
# gpsp now polls every .2 seconds for new data, storing it in self.current_value
while 1:
    # In the main thread, every 5 seconds print the current value

Update (May 6, 2023): I found a better solution: the gpsd-py3 library works great.

Leave a Reply

Your email address will not be published. Required fields are marked *