summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEric S. Raymond <esr@thyrsus.com>2016-03-22 04:11:28 -0400
committerEric S. Raymond <esr@thyrsus.com>2016-03-22 04:11:28 -0400
commitc904362d06f325e2d3c1bcdebd702b5d274a1cdd (patch)
tree6b4f58444faacbac894fb042af363c1d6e1a89c3
parent8200880a4949fd112674551374868f292b8a6524 (diff)
downloadgpsd-c904362d06f325e2d3c1bcdebd702b5d274a1cdd.tar.gz
Forward-port gps/ Python client code to run polyglot under Python 2 or 3.
Verified by testing gpsprof under both versions. leapecond.py is also OK. Not yet polyglot: gegps, gpscap.py, gpscat, gpsfake, jsongen.py, maskaudit.py, test_maidenhead.py, valgrind_audit.py, xgps, xgpsspeed.
-rw-r--r--gps/__init__.py4
-rw-r--r--gps/client.py18
-rw-r--r--gps/fake.py22
-rwxr-xr-xgps/gps.py14
-rw-r--r--gps/misc.py8
-rwxr-xr-xgpsprof11
-rwxr-xr-xleapsecond.py3
7 files changed, 45 insertions, 35 deletions
diff --git a/gps/__init__.py b/gps/__init__.py
index cb73669c..05bce897 100644
--- a/gps/__init__.py
+++ b/gps/__init__.py
@@ -6,8 +6,8 @@
api_major_version = 5 # bumped on incompatible changes
api_minor_version = 0 # bumped on compatible changes
-from gps import *
-from misc import *
+from .gps import *
+from .misc import *
# The 'client' module exposes some C utility functions for Python clients.
# The 'packet' module exposes the packet getter via a Python interface.
diff --git a/gps/client.py b/gps/client.py
index 6a996714..2ff06f93 100644
--- a/gps/client.py
+++ b/gps/client.py
@@ -1,7 +1,7 @@
# This file is Copyright (c) 2010 by the GPSD project
# BSD terms apply: see the file COPYING in the distribution root for details.
#
-import time, socket, sys, select, exceptions
+import time, socket, sys, select
if sys.hexversion >= 0x2060000:
import json # For Python 2.6
@@ -11,9 +11,9 @@ else:
GPSD_PORT = "2947"
-class json_error(exceptions.Exception):
+class json_error(BaseException):
def __init__(self, data, explanation):
- exceptions.Exception.__init__(self)
+ BaseException.__init__(self)
self.data = data
self.explanation = explanation
@@ -42,7 +42,7 @@ class gpscommon:
try:
port = int(port)
except ValueError:
- raise socket.error, "nonnumeric port"
+ raise socket.error("nonnumeric port")
# if self.verbose > 0:
# print 'connect:', (host, port)
msg = "getaddrinfo returns an empty list"
@@ -53,13 +53,13 @@ class gpscommon:
self.sock = socket.socket(af, socktype, proto)
# if self.debuglevel > 0: print 'connect:', (host, port)
self.sock.connect(sa)
- except socket.error, msg:
+ except socket.error(msg):
# if self.debuglevel > 0: print 'connect fail:', (host, port)
self.close()
continue
break
if not self.sock:
- raise socket.error, msg
+ raise socket.error(msg)
def close(self):
if self.sock:
@@ -82,7 +82,7 @@ class gpscommon:
sys.stderr.write("poll: reading from daemon...\n")
eol = self.linebuffer.find('\n')
if eol == -1:
- frag = self.sock.recv(4096)
+ frag = self.sock.recv(4096).decode('ascii')
self.linebuffer += frag
if self.verbose > 1:
sys.stderr.write("poll: read complete.\n")
@@ -123,7 +123,7 @@ class gpscommon:
"Ship commands to the daemon."
if not commands.endswith("\n"):
commands += "\n"
- self.sock.send(commands)
+ self.sock.send(commands.encode('ascii'))
WATCH_ENABLE = 0x000001 # enable streaming
WATCH_DISABLE = 0x000002 # disable watching
@@ -147,7 +147,7 @@ class gpsjson:
def unpack(self, buf):
try:
self.data = dictwrapper(json.loads(buf.strip(), encoding="ascii"))
- except ValueError, e:
+ except ValueError(e):
raise json_error(buf, e.args[0])
# Should be done for any other array-valued subobjects, too.
# This particular logic can fire on SKY or RTCM2 objects.
diff --git a/gps/fake.py b/gps/fake.py
index cadd68d5..13fa542d 100644
--- a/gps/fake.py
+++ b/gps/fake.py
@@ -67,8 +67,10 @@ To allow for adding and removing clients while the test is running,
run in threaded mode by calling the start() method. This simply calls
the run method in a subthread, with locking of critical regions.
"""
+from __future__ import print_function
+
import os, sys, time, signal, pty, termios # fcntl, array, struct
-import exceptions, threading, socket, select
+import threading, socket, select
import gps
import packet as sniffer
import stat
@@ -114,9 +116,9 @@ def GetDelay(slow=False):
return delay
-class TestLoadError(exceptions.Exception):
+class TestLoadError(BaseException):
def __init__(self, msg):
- exceptions.Exception.__init__(self)
+ BaseException.__init__(self)
self.msg = msg
@@ -190,7 +192,7 @@ class TestLoad:
if type_latch is None:
type_latch = ptype
if self.predump:
- print repr(packet)
+ print(repr(packet))
if not packet:
raise TestLoadError("zero-length packet from %s" %
self.name)
@@ -209,9 +211,9 @@ class TestLoad:
self.sentences.append("# EOF\n")
-class PacketError(exceptions.Exception):
+class PacketError(BaseException):
def __init__(self, msg):
- exceptions.Exception.__init__(self)
+ BaseException.__init__(self)
self.msg = msg
@@ -421,9 +423,9 @@ class FakeUDP(FakeGPS):
pass # shutdown() fails on UDP
-class DaemonError(exceptions.Exception):
+class DaemonError(BaseException):
def __init__(self, msg):
- exceptions.Exception.__init__(self)
+ BaseException.__init__(self)
self.msg = msg
def __str__(self):
@@ -546,9 +548,9 @@ class DaemonInstance:
self.pid = None
-class TestSessionError(exceptions.Exception):
+class TestSessionError(BaseException):
def __init__(self, msg):
- exceptions.Exception.__init__(self)
+ BaseException.__init__(self)
self.msg = msg
diff --git a/gps/gps.py b/gps/gps.py
index 1a0f5524..eff96552 100755
--- a/gps/gps.py
+++ b/gps/gps.py
@@ -14,8 +14,10 @@
# The JSON parts of this (which will be reused by any new interface)
# now live in a different module.
#
-from client import *
-from misc import isotime
+from __future__ import print_function
+
+from .client import *
+from .misc import isotime
NaN = float('nan')
@@ -286,7 +288,7 @@ class gps(gpscommon, gpsdata, gpsjson):
if type(self.fix.time) == type(0.0):
self.fix.time = self.utc
else:
- self.fix.time = isotime(self.utc.encode("ascii"))
+ self.fix.time = isotime(self.utc)
self.fix.ept = default("ept", NaN, TIMERR_SET)
self.fix.latitude = default("lat", NaN, LATLON_SET)
self.fix.longitude = default("lon", NaN)
@@ -372,7 +374,7 @@ if __name__ == '__main__':
if switch == '-v':
verbose = True
if len(arguments) > 2:
- print 'Usage: gps.py [-v] [host [port]]'
+ print('Usage: gps.py [-v] [host [port]]')
sys.exit(1)
opts = {"verbose": verbose}
@@ -385,9 +387,9 @@ if __name__ == '__main__':
session.stream(WATCH_ENABLE)
try:
for report in session:
- print report
+ print(report)
except KeyboardInterrupt:
# Avoid garble on ^C
- print ""
+ print("")
# gps.py ends here
diff --git a/gps/misc.py b/gps/misc.py
index b34f627a..5f8bc44c 100644
--- a/gps/misc.py
+++ b/gps/misc.py
@@ -55,8 +55,10 @@ def CalcRad(lat):
return r
-def EarthDistance((lat1, lon1), (lat2, lon2)):
+def EarthDistance(c1, c2):
"Distance in meters between two points specified in degrees."
+ (lat1, lon1) = c1
+ (lat2, lon2) = c2
x1 = CalcRad(lat1) * math.cos(Deg2Rad(lon1)) * math.sin(Deg2Rad(90 - lat1))
x2 = CalcRad(lat2) * math.cos(Deg2Rad(lon2)) * math.sin(Deg2Rad(90 - lat2))
y1 = CalcRad(lat1) * math.sin(Deg2Rad(lon1)) * math.sin(Deg2Rad(90 - lat1))
@@ -75,8 +77,10 @@ def EarthDistance((lat1, lon1), (lat2, lon2)):
return CalcRad((lat1 +lat2) / 2) * math.acos(a)
-def MeterOffset((lat1, lon1), (lat2, lon2)):
+def MeterOffset(c1, c2):
"Return offset in meters of second arg from first."
+ (lat1, lon1) = c1
+ (lat2, lon2) = c2
dx = EarthDistance((lat1, lon1), (lat1, lon2))
dy = EarthDistance((lat1, lon1), (lat2, lon1))
if lat1 < lat2:
diff --git a/gpsprof b/gpsprof
index 15374de4..63090048 100755
--- a/gpsprof
+++ b/gpsprof
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python
#
# This file is Copyright (c) 2010 by the GPSD project
# BSD terms apply: see the file COPYING in the distribution root for details.
@@ -6,6 +6,7 @@
# Collect and plot latency-profiling data from a running gpsd.
# Requires gnuplot.
#
+# This code runs under both Python 2 and Python 3. Preserve this property!
import copy
import getopt
import gps
@@ -183,7 +184,7 @@ class spaceplot(plotter):
# centroid is just arithmetic avg of lat,lon
self.centroid = (sum([x[0] for x in self.fixes]) / len(self.fixes), sum([x[1] for x in self.fixes]) / len(self.fixes))
# Sort fixes by distance from centroid
- self.fixes.sort(lambda x, y: cmp(self.d(self.centroid, x), self.d(self.centroid, y)))
+ self.fixes.sort(key=lambda p: self.d(self.centroid, p))
# Convert fixes to offsets from centroid in meters
self.recentered = [gps.MeterOffset(self.centroid, fix[:2]) for fix in self.fixes]
@@ -219,8 +220,8 @@ class spaceplot(plotter):
else:
alt_avg = alt_sum / alt_num
# Sort fixes by distance from average altitude
- alt_fixes.sort(lambda x, y: cmp(abs(alt_avg - x), abs(alt_avg - y)))
- alt_ep = abs(alt_fixes[len(alt_fixes) / 2] - alt_avg)
+ alt_fixes.sort(key=lambda a: abs(alt_avg - a))
+ alt_ep = abs(alt_fixes[len(alt_fixes) // 2] - alt_avg)
if self.centroid[0] < 0:
latstring = "%fS" % -self.centroid[0]
elif self.centroid[0] == 0:
@@ -246,7 +247,7 @@ class spaceplot(plotter):
fmt += 'set y2label "Meters Altitude from %f"\n' % alt_avg
fmt += 'set ytics nomirror\n'
fmt += 'set y2tics\n'
- fmt += 'cep=%f\n' % self.d((0, 0), self.recentered[len(self.fixes) / 2])
+ fmt += 'cep=%f\n' % self.d((0, 0), self.recentered[len(self.fixes) // 2])
fmt += 'cep95=%f\n' % self.d((0, 0), self.recentered[int(len(self.fixes) * 0.95)])
fmt += 'cep99=%f\n' % self.d((0, 0), self.recentered[int(len(self.fixes) * 0.99)])
fmt += 'set parametric\n'
diff --git a/leapsecond.py b/leapsecond.py
index e778d236..89c38661 100755
--- a/leapsecond.py
+++ b/leapsecond.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python
"""
Usage: leapsecond.py [-v] { [-h] | [-f filename] | [-g filename] | [-H filename]
@@ -43,6 +43,7 @@ This file is Copyright (c) 2013 by the GPSD project
BSD terms apply: see the file COPYING in the distribution root for details.
"""
+# This code runs under both Python 2 and Python 3. Preserve this property!
from __future__ import print_function
import os, urllib, re, random, time, calendar, math, sys, signal