summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEric S. Raymond <esr@thyrsus.com>2016-03-22 03:08:21 -0400
committerEric S. Raymond <esr@thyrsus.com>2016-03-22 03:08:21 -0400
commit8200880a4949fd112674551374868f292b8a6524 (patch)
tree5332fe0413615a729c4953d43cba7a7ea7a1a17f
parent254022f6c77e55280c6da59a01ee5225abdf7bcb (diff)
downloadgpsd-8200880a4949fd112674551374868f292b8a6524.tar.gz
Forward-port Python utilities to run polyglot under either Python 2 or 3.
For the moment most shebang lines still say 'python2' rather than just 'python'. This is because the client code in gps/ hasn't been touched yet; the internal imports break under Python 3 and that needs to be fixed.
-rw-r--r--build.txt2
-rwxr-xr-xgegps6
-rw-r--r--gpscap.py25
-rwxr-xr-xgpscat16
-rwxr-xr-xgpsfake60
-rwxr-xr-xgpsprof6
-rw-r--r--gpssim.py24
-rw-r--r--jsongen.py.in32
-rwxr-xr-xleapsecond.py69
-rw-r--r--maskaudit.py.in27
-rwxr-xr-xtest_maidenhead.py8
-rw-r--r--valgrind-audit.py.in52
-rwxr-xr-xxgps7
-rwxr-xr-xxgpsspeed12
14 files changed, 186 insertions, 160 deletions
diff --git a/build.txt b/build.txt
index 01fb4723..ee20a584 100644
--- a/build.txt
+++ b/build.txt
@@ -56,7 +56,7 @@ Necessary components for any build:
|============================================================================
|C compiler | gpsd and client library are written in C
-|Python 2.x, x >= 6 | some code is generated from python scripts
+|Python 2.x, x >= 7 | some code is generated from python scripts
|scons | for executing the build recipe
|============================================================================
diff --git a/gegps b/gegps
index 19623dbc..a4d00911 100755
--- a/gegps
+++ b/gegps
@@ -20,6 +20,8 @@
# Modified by Chen Wei <weichen302@aol.com> for use with gpsd
# Cleaned up and adapted for the GPSD project by Eric S. Raymond.
+from __future__ import print_function
+
import sys, os, getopt
import gps
@@ -87,7 +89,7 @@ if __name__ == "__main__":
else:
try:
while True:
- report = session.next()
+ report = next(session)
if report['class'] == 'TPV':
f = open(os.path.join(kmldir, 'Realtime_GPS.kml'), 'w')
f.write(kmlize(report))
@@ -95,6 +97,6 @@ if __name__ == "__main__":
except StopIteration:
pass
except KeyboardInterrupt:
- print 'gegpsd stopped '
+ print('gegpsd stopped ')
# end
diff --git a/gpscap.py b/gpscap.py
index 422ecb93..998d2f7a 100644
--- a/gpscap.py
+++ b/gpscap.py
@@ -1,17 +1,20 @@
"""
-
gpscap - GPS/AIS capability dictionary class.
This file is Copyright (c) 2010 by the GPSD project
BSD terms apply: see the file COPYING in the distribution root for details.
"""
-import ConfigParser
+from __future__ import print_function
+try:
+ import configparser
+except ImportError:
+ import ConfigParser as configparser
-class GPSDictionary(ConfigParser.RawConfigParser):
+class GPSDictionary(configparser.RawConfigParser):
def __init__(self, *files):
"Initialize the capability dictionary"
- ConfigParser.RawConfigParser.__init__(self)
+ configparser.RawConfigParser.__init__(self)
if not files:
files = ["gpscap.ini", "/usr/share/gpsd/gpscap.ini"]
self.read(files)
@@ -36,9 +39,9 @@ class GPSDictionary(ConfigParser.RawConfigParser):
# Sanity check: All items must have a type field.
for section in self.sections():
if not self.has_option(section, "type"):
- raise ConfigParser.Error("%s has no type" % section)
+ raise configparser.Error("%s has no type" % section)
elif self.get(section, "type") not in ("engine", "vendor", "device"):
- raise ConfigParser.Error("%s has invalid type" % section)
+ raise configparser.Error("%s has invalid type" % section)
# Sanity check: All devices must point at a vendor object.
# Side effect: build the lists of vendors and devices.
self.vendors = []
@@ -52,9 +55,9 @@ class GPSDictionary(ConfigParser.RawConfigParser):
for section in self.sections():
if self.get(section, "type") == "device":
if not self.has_option(section, "vendor"):
- raise ConfigParser.Error("%s has no vendor" % section)
+ raise configparser.Error("%s has no vendor" % section)
if self.get(section, "vendor") not in self.vendors:
- raise ConfigParser.Error("%s has invalid vendor" % section)
+ raise configparser.Error("%s has invalid vendor" % section)
def HTMLDump(self, ofp):
thead = """<table style='border:1px solid gray;font-size:small;background-color:#CCCCCC'>
@@ -167,6 +170,6 @@ if __name__ == "__main__":
try:
d = GPSDictionary()
d.HTMLDump(sys.stdout)
- except ConfigParser.Error, e:
- print >>sys.stderr, sys.argv[0]+":", e
- raise SystemExit, 1
+ except configparser.Error as e:
+ sys.stderr.write(sys.argv[0]+":%s\n" % e)
+ raise SystemExit(1)
diff --git a/gpscat b/gpscat
index c401397c..17a68052 100755
--- a/gpscat
+++ b/gpscat
@@ -5,6 +5,8 @@
#
# Display GPS output. Hexify it if necessary.
#
+from __future__ import print_function
+
import os, sys, termios, socket, select, getopt, curses.ascii
import gps.packet as sniffer
@@ -42,9 +44,9 @@ if __name__ == '__main__':
try:
try:
(options, arguments) = getopt.getopt(sys.argv[1:], "hps:tD:V")
- except getopt.GetoptError, msg:
- print "gpscat: " + str(msg)
- raise SystemExit, 1
+ except getopt.GetoptError as msg:
+ print("gpscat: " + str(msg))
+ raise SystemExit(1)
speed = None
parity = None
@@ -67,11 +69,11 @@ if __name__ == '__main__':
debuglevel = BASELEVEL + int(val)
elif switch == '-h':
printusage()
- raise SystemExit, 0
+ raise SystemExit(0)
if len(arguments) != 1:
printusage()
- raise SystemExit, 1
+ raise SystemExit(1)
if "rfcomm" in arguments[0]: # Bluetooth special case
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
@@ -86,7 +88,7 @@ if __name__ == '__main__':
ispeed = ospeed = eval("termios.B%d" % speed)
except AttributeError:
sys.stderr.write("gpscat: unknown baud rate %d\n" % speed)
- raise SystemExit, 1
+ raise SystemExit(1)
if stopbits:
cflag &= ~termios.CSIZE
cflag |= (termios.CS8, termios.CS7)[stopbits-1]
@@ -133,7 +135,7 @@ if __name__ == '__main__':
except KeyboardInterrupt:
if rawmode:
sys.stdout.write("\n")
- raise SystemExit, 0
+ raise SystemExit(0)
# Local variables:
# mode: python
diff --git a/gpsfake b/gpsfake
index 6c333969..6977e9b0 100755
--- a/gpsfake
+++ b/gpsfake
@@ -9,6 +9,8 @@
# This file is Copyright (c) 2010 by the GPSD project
# BSD terms apply: see the file COPYING in the distribution root for details.
+from __future__ import print_function
+
import getopt
import gps
import gps.fake as gpsfake # The "as" pacifies pychecker
@@ -19,6 +21,10 @@ import socket
import sys
import time
+try:
+ my_input = raw_input
+except NameError:
+ my_input = input
class Baton:
"Ship progress indications to stderr."
@@ -70,8 +76,8 @@ def hexdump(s):
def fakehook(linenumber, fakegps):
if len(fakegps.testload.sentences) == 0:
- print >>sys.stderr, "fakegps: no sentences in test load."
- raise SystemExit, 1
+ sys.stderr.write("fakegps: no sentences in test load.\n")
+ raise SystemExit(1)
if linenumber % len(fakegps.testload.sentences) == 0:
if singleshot and linenumber > 0:
return False
@@ -86,9 +92,9 @@ def fakehook(linenumber, fakegps):
ml = hexdump(ml)
announce = fakegps.testload.legend % (linenumber % len(fakegps.testload.sentences) + 1) + ml
if promptme:
- raw_input(announce + "? ")
+ my_input(announce + "? ")
else:
- print announce
+ print(announce)
if progress:
baton.twirl()
return True
@@ -96,9 +102,9 @@ def fakehook(linenumber, fakegps):
if __name__ == '__main__':
try:
(options, arguments) = getopt.getopt(sys.argv[1:], "1bc:D:ghilm:no:pP:r:s:StTuvx")
- except getopt.GetoptError, msg:
- print "gpsfake: " + str(msg)
- raise SystemExit, 1
+ except getopt.GetoptError as msg:
+ print("gpsfake: " + str(msg))
+ raise SystemExit(1)
port = None
progress = False
@@ -153,29 +159,29 @@ if __name__ == '__main__':
tcp = True
elif switch == '-T':
sys.stdout.write("sys %s platform %s: WRITE_PAD = %.5f\n" % (sys.platform, platform.platform(), gpsfake.GetDelay(slow)))
- raise SystemExit, 0
+ raise SystemExit(0)
elif switch == '-u':
udp = True
elif switch == '-v':
verbose += 1
elif switch == '-h':
sys.stderr.write("usage: gpsfake [-h] [-l] [-m monitor] [--D debug] [-o options] [-p] [-s speed] [-S] [-c cycle] [-b] logfile\n")
- raise SystemExit, 0
+ raise SystemExit(0)
try:
pty.openpty()
except (AttributeError, OSError):
- print >>sys.stderr, "gpsfake: ptys not available, falling back to UDP."
+ sys.stderr.write("gpsfake: ptys not available, falling back to UDP.\n")
udp = True
if not arguments:
- print >>sys.stderr, "gpsfake: requires at least one logfile argument."
- raise SystemExit, 1
+ sys.stderr.write("gpsfake: requires at least one logfile argument.\n")
+ raise SystemExit(1)
if progress:
baton = Baton("Processing %s" % ",".join(arguments), "done")
else:
- print >>sys.stderr, "Processing %s" % ",".join(arguments)
+ sys.stderr.write("Processing %s\n" % ",".join(arguments))
# Don't allocate a private port when cycling logs for client testing.
if port is None and not pipe:
@@ -195,24 +201,24 @@ if __name__ == '__main__':
for logfile in arguments:
try:
test.gps_add(logfile, speed=speed, pred=fakehook, oneshot=singleshot)
- except gpsfake.TestLoadError, e:
+ except gpsfake.TestLoadError as e:
sys.stderr.write("gpsfake: " + e.msg + "\n")
- raise SystemExit, 1
- except gpsfake.PacketError, e:
+ raise SystemExit(1)
+ except gpsfake.PacketError as e:
sys.stderr.write("gpsfake: " + e.msg + "\n")
- raise SystemExit, 1
- except gpsfake.DaemonError, e:
+ raise SystemExit(1)
+ except gpsfake.DaemonError as e:
sys.stderr.write("gpsfake: " + e.msg + "\n")
- raise SystemExit, 1
- except IOError, e:
+ raise SystemExit(1)
+ except IOError as e:
if e.filename is None:
sys.stderr.write("gpsfake: unknown internal I/O error %s\n" % e)
else:
sys.stderr.write("gpsfake: no such file as %s or file unreadable\n" % e.filename)
- raise SystemExit, 1
+ raise SystemExit(1)
except OSError:
sys.stderr.write("gpsfake: can't open pty.\n")
- raise SystemExit, 1
+ raise SystemExit(1)
try:
if pipe:
@@ -228,15 +234,15 @@ if __name__ == '__main__':
# calls to gpsd_set_speed() in isync_detect()
time.sleep(1.4)
test.run()
- except socket.error, msg:
+ except socket.error as msg:
sys.stderr.write("gpsfake: socket error %s.\n" % msg)
- raise SystemExit, 1
- except gps.client.json_error, e:
+ raise SystemExit(1)
+ except gps.client.json_error as e:
sys.stderr.write("gpsfake: JSON error on line %s is %s.\n" % (repr(e.data), e.explanation))
- raise SystemExit, 1
+ raise SystemExit(1)
except KeyboardInterrupt:
sys.stderr.write("gpsfake: aborted\n")
- raise SystemExit, 1
+ raise SystemExit(1)
finally:
test.cleanup()
diff --git a/gpsprof b/gpsprof
index 2c124769..15374de4 100755
--- a/gpsprof
+++ b/gpsprof
@@ -181,11 +181,11 @@ class spaceplot(plotter):
def postprocess(self):
if not self.recentered:
# centroid is just arithmetic avg of lat,lon
- self.centroid = (sum(map(lambda x: x[0], self.fixes)) / len(self.fixes), sum(map(lambda x: x[1], self.fixes)) / len(self.fixes))
+ 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)))
# Convert fixes to offsets from centroid in meters
- self.recentered = map(lambda fix: gps.MeterOffset(self.centroid, fix[:2]), self.fixes)
+ self.recentered = [gps.MeterOffset(self.centroid, fix[:2]) for fix in self.fixes]
def data(self):
res = ""
@@ -446,7 +446,7 @@ if __name__ == '__main__':
elif switch == '-h':
sys.stderr.write(
"usage: gpsprof [-h] [-D debuglevel] [-m threshold] [-n samplecount] [-d]\n"
- + "\t[-f {" + "|".join(map(lambda x: x.name, formatters)) + "}] [-s speed] [-t title] [-T terminal] [server[:port[:device]]]\n")
+ + "\t[-f {" + "|".join([x.name for x in formatters]) + "}] [-s speed] [-t title] [-T terminal] [server[:port[:device]]]\n")
sys.exit(0)
(host, port, device) = ("localhost", "2947", None)
diff --git a/gpssim.py b/gpssim.py
index a4dc4a82..fb686e67 100644
--- a/gpssim.py
+++ b/gpssim.py
@@ -5,7 +5,7 @@ A GPS simulator.
This is proof-of-concept code, not production ready; some functions are stubs.
"""
-import sys, math, random, exceptions, time
+import sys, math, random, time
import gps, gpslib
# First, the mathematics. We simulate a moving viewpoint on the Earth
@@ -77,9 +77,9 @@ class satellite:
# class to generate output.
-class gpssimException(exceptions.Exception):
+class gpssimException(BaseException):
def __init__(self, message, filename, lineno):
- exceptions.Exception.__init__(self)
+ BaseException.__init__(self)
self.message = message
self.filename = filename
self.lineno = lineno
@@ -90,14 +90,14 @@ class gpssimException(exceptions.Exception):
class gpssim:
"Simulate a moving sensor, with skyview."
- active_PRNs = range(1, 24 + 1) + [134, ]
+ active_PRNs = list(range(1, 24 + 1)) + [134, ]
def __init__(self, outfmt):
self.ksv = ksv()
self.ephemeris = {}
# This sets up satellites at random. Not really what we want.
for prn in gpssim.active_PRNs:
- for (prn, _satellite) in self.ephemeris.items():
+ for (prn, _satellite) in list(self.ephemeris.items()):
self.skyview[prn] = (random.randint(-60, +61),
random.randint(0, 359))
self.have_ephemeris = False
@@ -122,7 +122,7 @@ class gpssim:
if command == "time":
self.ksv.time = gps.isotime(fields[1])
elif command == "location":
- (self.lat, self.lon, self.alt) = map(float, fields[1:])
+ (self.lat, self.lon, self.alt) = list(map(float, fields[1:]))
elif command == "course":
self.ksv.time = float(fields[1])
elif command == "speed":
@@ -130,7 +130,7 @@ class gpssim:
elif command == "climb":
self.ksv.climb = float(fields[1])
elif command == "acceleration":
- (self.ksv.h_acc, self.ksv.h_acc) = map(float, fields[1:])
+ (self.ksv.h_acc, self.ksv.h_acc) = list(map(float, fields[1:]))
elif command == "snr":
self.channels[int(fields[1])] = float(fields[2])
elif command == "go":
@@ -170,10 +170,10 @@ class gpssim:
def go(self, seconds):
"Run the simulation for a specified number of seconds."
for i in range(seconds):
- self.ksv.next()
+ next(self.ksv)
if self.have_ephemeris:
self.skyview = {}
- for (prn, satellite) in self.ephemeris.items():
+ for (prn, satellite) in list(self.ephemeris.items()):
self.skyview[prn] = satellite.position(i)
self.output.write(self.gpstype.report(self))
@@ -295,7 +295,7 @@ class NMEA:
(interval, sentence) = sentence
if self.counter % interval:
continue
- out += apply(getattr(self, sentence), [sim])
+ out += getattr(self, sentence)(*[sim])
self.counter += 1
return out
@@ -304,7 +304,7 @@ class NMEA:
if __name__ == "__main__":
try:
gpssim(NMEA).filter(sys.stdin, sys.stdout)
- except gpssimException, e:
- print >>sys.stderr, e
+ except gpssimException as e:
+ sys.stderr.write(repr(e)+"\n")
# gpssim.py ends here.
diff --git a/jsongen.py.in b/jsongen.py.in
index 8155e43e..f3121de0 100644
--- a/jsongen.py.in
+++ b/jsongen.py.in
@@ -10,6 +10,8 @@
# This code generates template declarations for AIS-JSON parsing from a
# declarative specification of a JSON structure.
#
+from __future__ import print_function
+
import sys, getopt
#
@@ -934,9 +936,9 @@ def generate(spec):
attributes = [t[0] for t in spec["fieldmap"]]
for attr in spec.get("stringbuffered", []):
if attr not in attributes:
- print >>sys.stderr, "buffered %s is not in base attributes of %s"\
- % (attr, initname)
- raise SystemExit, 1
+ sys.stderr.write("buffered %s is not in base attributes of %s\n"
+ % (attr, initname))
+ raise SystemExit(1)
elif attr not in outboard:
report += " char %s[JSON_VAL_MAX+1];\n" % attr
outboard.append(attr)
@@ -958,8 +960,8 @@ def generate(spec):
elif default:
report += leader + ".len = %s},\n" % (default,)
else:
- print >>sys.stderr, "explicit length specification required"
- raise SystemExit, 1
+ sys.stderr.write("explicit length specification required\n")
+ raise SystemExit(1)
report += """\
{NULL}
};
@@ -999,7 +1001,7 @@ def generate(spec):
{NULL}
};
"""
- print report
+ print(report)
if __name__ == '__main__':
try:
@@ -1007,9 +1009,9 @@ if __name__ == '__main__':
# In the future, this script will generate more different kinds
# of code.
(options, arguments) = getopt.getopt(sys.argv[1:], "", ["ais", "target="])
- except getopt.GetoptError, msg:
- print "jsongen.py: " + str(msg)
- raise SystemExit, 1
+ except getopt.GetoptError as msg:
+ print("jsongen.py: " + str(msg))
+ raise SystemExit(1)
spec = None
target = None
@@ -1020,26 +1022,26 @@ if __name__ == '__main__':
target = val
if not target or not spec:
- print "jsongen.py: must specify type and target."
- raise SystemExit, 1
+ print("jsongen.py: must specify type and target.")
+ raise SystemExit(1)
if target == 'parser':
- print """/*
+ print("""/*
* This is code generated by jsongen.py. Do not hand-hack it!
*/
#define NITEMS(x) (int)(sizeof(x)/sizeof(x[0]))
/*@ -fullinitblock */
-"""
+""")
outboard = []
for description in spec:
generate(description)
- print """
+ print("""
/*@ +fullinitblock */
/* Generated code ends. */
-"""
+""")
# The following sets edit modes for GNU EMACS
# Local Variables:
# mode:python
diff --git a/leapsecond.py b/leapsecond.py
index 783cae33..e778d236 100755
--- a/leapsecond.py
+++ b/leapsecond.py
@@ -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.
"""
+from __future__ import print_function
import os, urllib, re, random, time, calendar, math, sys, signal
@@ -94,7 +95,7 @@ def isotime(s):
msec = s - date
date = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s))
return date + "." + repr(msec)[3:]
- elif type(s) == type("") or type(s) == type(u""):
+ elif type(s) == type("") or type(s) == type(""):
if s[-1] == "Z":
s = s[:-1]
if "." in s:
@@ -120,13 +121,13 @@ def retrieve():
txt = ifp.read()
ifp.close()
if verbose:
- print >>sys.stderr, "%s" % txt
+ sys.stderr.write("%s\n" % txt)
m = re.search(regexp, txt)
if m:
return int(m.group(1)) * sign - offset
except IOError:
if verbose:
- print >>sys.stderr, "IOError: %s" % url
+ sys.stderr.write("IOError: %s\n" % url)
return None
@@ -163,14 +164,14 @@ def save_leapseconds(outfile):
try:
fetchobj = urllib.urlopen(url)
except IOError:
- print >>sys.stderr, "Fetch from %s failed." % url
+ sys.stderr.write("Fetch from %s failed.\n" % url)
continue
# This code assumes that after 1980, leap-second increments are
# always integrally one second and every increment is listed here
fp = open(outfile, "w")
for line in fetchobj:
if verbose:
- print >>sys.stderr, "%s" % line[:-1]
+ sys.stderr.write("%s\n" % line[:-1])
if line.startswith(" 1980"):
skip = False
if skip:
@@ -180,11 +181,11 @@ def save_leapseconds(outfile):
continue
md = leapbound(fields[0], fields[1])
if verbose:
- print >>sys.stderr, "# %s" % md
+ sus.stderr.write("# %s\n" % md)
fp.write(repr(iso_to_unix(md)) + "\t# " + str(md) + "\n")
fp.close()
return
- print >>sys.stderr, "%s not updated." % outfile
+ sys.stderr.write("%s not updated.\n" % outfile)
def fetch_leapsecs(filename):
@@ -292,9 +293,9 @@ def unix_to_iso(tv):
def graph_history(filename):
"Generate a GNUPLOT plot of the leap-second history."
raw = fetch_leapsecs(filename)
- (b, c, e) = leastsquares(zip(range(len(raw)), raw))
+ (b, c, e) = leastsquares(list(zip(list(range(len(raw))), raw)))
e /= (60 * 60 * 24 * 7)
- dates = map(lambda t: time.strftime("%Y-%m-%d", time.localtime(t)), raw)
+ dates = [time.strftime("%Y-%m-%d", time.localtime(t)) for t in raw]
enddate = time.strftime("%Y-%m-%d", time.localtime(raw[-1]+16416000)) # Adding 190 days to scale
fmt = ''
fmt += '# Least-squares approximation of Unix time from leapsecond is:\n'
@@ -314,7 +315,7 @@ def graph_history(filename):
for (i, (r, d)) in enumerate(zip(raw, dates)):
fmt += "%d\t%s\t%s\n" % (i, r, d)
fmt += 'e\n'
- print fmt
+ print(fmt)
def rfc822_to_unix(tv):
@@ -330,24 +331,24 @@ def unix_to_rfc822(tv):
def printnext(val):
"Compute Unix time correponsing to a scheduled leap second."
if val[:3].lower() not in ("jun", "dec"):
- print >>sys.stderr, "leapsecond.py: -n argument must begin with "\
- "'Jun' or 'Dec'"
- raise SystemExit, 1
+ sys.stderr.write("leapsecond.py: -n argument must begin with "\
+ "'Jun' or 'Dec'\n")
+ raise SystemExit(1)
else:
month = val[:3].lower()
if len(val) != 7:
- print >>sys.stderr, "leapsecond.py: -n argument must be of "\
- "the form {jun|dec}nnnn."
- raise SystemExit, 1
+ sys.stderr.wrrite("leapsecond.py: -n argument must be of "\
+ "the form {jun|dec}nnnn.\n")
+ raise SystemExit(1)
try:
year = int(val[3:])
except ValueError:
- print >>sys.stderr, "leapsecond.py: -n argument must end "\
- "with a 4-digit year."
- raise SystemExit, 1
+ sys.stderr.write("leapsecond.py: -n argument must end "\
+ "with a 4-digit year.\n")
+ raise SystemExit(1)
# Date looks valid
tv = leapbound(year, month)
- print "%d /* %s */" % (iso_to_unix(tv), tv)
+ print("%d /* %s */" % (iso_to_unix(tv), tv))
def leapbound(year, month):
@@ -368,8 +369,8 @@ def leapbound(year, month):
def usage():
- print __doc__
- raise SystemExit, 0
+ print(__doc__)
+ raise SystemExit(0)
if __name__ == '__main__':
import getopt
@@ -381,27 +382,27 @@ if __name__ == '__main__':
verbose = 1
elif switch == '-f': # Fetch USNO data to cache locally
save_leapseconds(val)
- raise SystemExit, 0
+ raise SystemExit(0)
elif switch == '-g': # Graph the leap_second history
graph_history(val)
- raise SystemExit, 0
+ raise SystemExit(0)
elif switch == '-H': # make leapsecond include
sys.stdout.write(make_leapsecond_include(val))
- raise SystemExit, 0
+ raise SystemExit(0)
elif switch == '-i': # Compute Unix time from RFC822 date
- print rfc822_to_unix(val)
- raise SystemExit, 0
+ print(rfc822_to_unix(val))
+ raise SystemExit(0)
elif switch == '-n': # Compute possible next leapsecond
printnext(val)
- raise SystemExit, 0
+ raise SystemExit(0)
elif switch == '-o': # Compute RFC822 date from Unix time
- print unix_to_rfc822(float(val))
- raise SystemExit, 0
+ print(unix_to_rfc822(float(val)))
+ raise SystemExit(0)
elif switch == '-I': # Compute Unix time from ISO8601 date
- print isotime(val)
- raise SystemExit, 0
+ print(isotime(val))
+ raise SystemExit(0)
elif switch == '-O': # Compute ISO8601 date from Unix time
- print isotime(float(val))
- raise SystemExit, 0
+ print(isotime(float(val)))
+ raise SystemExit(0)
# End
diff --git a/maskaudit.py.in b/maskaudit.py.in
index 31be05ac..db6f57f8 100644
--- a/maskaudit.py.in
+++ b/maskaudit.py.in
@@ -11,11 +11,16 @@
#
# With -t, tabulate usage of defines to find unused ones. Requires -c or -d.
-import commands
+from __future__ import print_function
+
import getopt
import glob
import sys
+try:
+ from subprocess import getstatusoutput
+except ImportError:
+ from commands import getstatusoutput
class SourceExtractor:
def __init__(self, sourcefile, clientside):
@@ -39,11 +44,11 @@ class SourceExtractor:
self.primitive_masks.append((fields[1], fields[2]))
def in_library(self, flag):
- (status, _output) = commands.getstatusoutput("grep %s libgps_core.c libgps_json.c gpsctl.c" % flag)
+ (status, _output) = getstatusoutput("grep %s libgps_core.c libgps_json.c gpsctl.c" % flag)
return status == 0
def in_daemon(self, flag):
- (status, _output) = commands.getstatusoutput("grep %s %s" % (flag, " ".join(self.daemonfiles)))
+ (status, _output) = getstatusoutput("grep %s %s" % (flag, " ".join(self.daemonfiles)))
return status == 0
def relevant(self, flag):
@@ -82,14 +87,14 @@ if __name__ == '__main__':
banner = "Daemon"
if tabulate:
- print "%-14s %8s" % (" ", banner)
+ print("%-14s %8s" % (" ", banner))
for (flag, value) in source.masks:
- print "%-14s %8s" % (flag, source.relevant(flag))
+ print("%-14s %8s" % (flag, source.relevant(flag)))
if pythonize:
for (d, v) in source.masks:
if v[-1] == 'u':
v = v[:-1]
- print "%-15s\t= %s" % (d, v)
+ print("%-15s\t= %s" % (d, v))
if not pythonize and not tabulate:
maxout = 0
for (d, v) in source.primitive_masks:
@@ -100,7 +105,7 @@ if __name__ == '__main__':
if stem.endswith("_IS"):
stem = stem[:-3]
maxout += len(stem) + 1
- print """/* This code is generated. Do not hand-hack it! */
+ print("""/* This code is generated. Do not hand-hack it! */
/*
* Also, beware that it is something of a CPU hog when called on every packet.
@@ -118,15 +123,15 @@ const char *gps_maskdump(gps_mask_t set)
const struct {
gps_mask_t mask;
const char *name;
- } *sp, names[] = {""" % (maxout + 3,)
+ } *sp, names[] = {""" % (maxout + 3,))
for (flag, value) in clientside.primitive_masks + daemonside.primitive_masks:
stem = flag
if stem.endswith("_SET"):
stem = stem[:-4]
if stem.endswith("_IS"):
stem = stem[:-3]
- print " {%s,\t\"%s\"}," % (flag, stem)
- print '''\
+ print(" {%s,\t\"%s\"}," % (flag, stem))
+ print('''\
};
memset(buf, '\\0', sizeof(buf));
@@ -141,7 +146,7 @@ const char *gps_maskdump(gps_mask_t set)
(void)strlcat(buf, "}", sizeof(buf));
return buf;
}
-'''
+''')
except KeyboardInterrupt:
pass
diff --git a/test_maidenhead.py b/test_maidenhead.py
index 5463d01b..e8d5459d 100755
--- a/test_maidenhead.py
+++ b/test_maidenhead.py
@@ -7,6 +7,8 @@
# Test conversions generated using
# http://f6fvy.free.fr/qthLocator/
+from __future__ import print_function
+
import sys, gps.clienthelpers
errors = 0
@@ -18,11 +20,11 @@ for (lat, lon, maidenhead, location) in [
]:
converted = gps.clienthelpers.maidenhead(lat, lon)
if converted != maidenhead:
- print >>sys.stderr, "maidenhead test: from %s %s (%s) expected %s got %s" \
- % (lat, lon, location, maidenhead, converted)
+ sys.stderr.write("maidenhead test: from %s %s (%s) expected %s got %s\n" \
+ % (lat, lon, location, maidenhead, converted))
errors += 1
else:
- print "%s OK" % location
+ print("%s OK" % location)
if errors:
sys.exit(1)
diff --git a/valgrind-audit.py.in b/valgrind-audit.py.in
index 56e2517a..ea34a6a3 100644
--- a/valgrind-audit.py.in
+++ b/valgrind-audit.py.in
@@ -9,6 +9,8 @@
# This file is Copyright (c) 2010 by the GPSD project
# BSD terms apply: see the file COPYING in the distribution root for details.
#
+from __future__ import print_function
+
import sys, gps.fake
debuglevel = 1
@@ -19,81 +21,81 @@ test.progress = sys.stderr.write
try:
test.spawn()
- print "\n*** Test #1: Normal single-client-session behavior."
- print "**** Add a GPS.\n"
+ print("\n*** Test #1: Normal single-client-session behavior.")
+ print("**** Add a GPS.\n")
gps1 = test.gps_add("test/daemon/bu303-moving.log")
- print "\n**** Add and remove a client.\n"
+ print("\n**** Add and remove a client.\n")
c1 = test.client_add("w\n")
test.gather(3)
test.client_remove(c1)
- print "\n**** Remove the GPS."
+ print("\n**** Remove the GPS.")
test.gps_remove(gps1)
- print "*** Test #1 complete.\n"
+ print("*** Test #1 complete.\n")
test.wait(3)
######################################################################
- print "\n*** Test #2: Successive non-overlapping client sessions."
- print "**** Add a GPS.\n"
+ print("\n*** Test #2: Successive non-overlapping client sessions.")
+ print("**** Add a GPS.\n")
gps1 = test.gps_add("test/daemon/bu303-climbing.log")
- print "\n**** Add and remove first client.\n"
+ print("\n**** Add and remove first client.\n")
c1 = test.client_add("w\n")
test.gather(3)
test.client_remove(c1)
test.wait(3)
- print "\n**** Add and remove second client.\n"
+ print("\n**** Add and remove second client.\n")
c2 = test.client_add("w\n")
test.gather(3)
test.client_remove(c2)
test.wait(3)
- print "\n**** Remove the GPS."
+ print("\n**** Remove the GPS.")
test.gps_remove(gps1)
- print "*** Test #2 complete.\n"
+ print("*** Test #2 complete.\n")
test.wait(3)
######################################################################
- print "\n*** Test #3: Overlapping client sessions."
- print "**** Add a GPS.\n"
+ print("\n*** Test #3: Overlapping client sessions.")
+ print("**** Add a GPS.\n")
gps1 = test.gps_add("test/daemon/bu303-climbing.log")
- print "\n**** Add first client.\n"
+ print("\n**** Add first client.\n")
c1 = test.client_add("w\n")
test.gather(2)
- print "\n**** Add second client.\n"
+ print("\n**** Add second client.\n")
c2 = test.client_add("w\n")
test.gather(3)
- print "\n**** Remove first client.\n"
+ print("\n**** Remove first client.\n")
test.client_remove(c1)
test.gather(2)
- print "\n**** Remove second client.\n"
+ print("\n**** Remove second client.\n")
test.client_remove(c2)
- print "\n**** Remove the GPS."
+ print("\n**** Remove the GPS.")
test.gps_remove(gps1)
- print "*** Test #3 complete.\n"
+ print("*** Test #3 complete.\n")
######################################################################
- print "\n*** Test #4: GPS removed while client still active."
- print "**** Add a GPS.\n"
+ print("\n*** Test #4: GPS removed while client still active.")
+ print("**** Add a GPS.\n")
gps1 = test.gps_add("test/daemon/bu303-moving.log")
- print "\n**** Add a client.\n"
+ print("\n**** Add a client.\n")
c1 = test.client_add("w\n")
test.gather(3)
- print "\n**** Remove the GPS."
+ print("\n**** Remove the GPS.")
test.gps_remove(gps1)
test.wait(3)
- print "\n**** Remove the client.\n"
+ print("\n**** Remove the client.\n")
test.client_remove(c1)
- print "*** Test #4 complete.\n"
+ print("*** Test #4 complete.\n")
finally:
test.cleanup()
diff --git a/xgps b/xgps
index 0ac20dbf..a57863fc 100755
--- a/xgps
+++ b/xgps
@@ -6,6 +6,8 @@ xgps -- test client for gpsd
usage: xgps [-D level] [-hV?] [-l degmfmt] [-u units] [server[:port[:device]]]
'''
+from __future__ import print_function
+
gui_about = '''\
This is xgps, a test client for the gpsd daemon.
@@ -642,8 +644,7 @@ class Base:
"AIS": self.aisbox}
# Discard field labels and associate data hooks with their widgets
- Base.gpsfields = map(lambda ((label, hook), widget): (hook, widget),
- zip(Base.gpsfields, gpswidgets))
+ Base.gpsfields = [(label_hook_widget[0][1], label_hook_widget[1]) for label_hook_widget in zip(Base.gpsfields, gpswidgets)]
def view_toggle(self, action):
# print "View toggle:", action.get_active(), action.get_name()
@@ -874,7 +875,7 @@ if __name__ == "__main__":
elif opt == '-u':
unit_system = val
elif opt in ('-?', '-h', '--help'):
- print __doc__
+ print(__doc__)
sys.exit(0)
elif opt == 'V':
sys.stderr.write("xgps 1.0\n")
diff --git a/xgpsspeed b/xgpsspeed
index 7bbf7c59..6e9957c4 100755
--- a/xgpsspeed
+++ b/xgpsspeed
@@ -296,7 +296,7 @@ class NauticalSpeedometer(Speedometer):
s_long = self.long_inset(rspeed)
s_middle = self.mid_inset(radius)
s_short = self.short_inset(radius)
- for i in xrange(11):
+ for i in range(11):
# draw the large ticks
alpha = (8 - i) * pi / 6
self.cr.move_to(*NauticalSpeedometer.polar2xy(rspeed, alpha, x, y))
@@ -308,7 +308,7 @@ class NauticalSpeedometer(Speedometer):
stxt = (self.maxspeed / 10) * i
self.draw_text(xf, yf, stxt, fontsize=radius / 15)
- for i in xrange(1, 11):
+ for i in range(1, 11):
# middle tick
alpha = (8 - i) * pi / 6
beta = (17 - 2 * i) * pi / 12
@@ -316,7 +316,7 @@ class NauticalSpeedometer(Speedometer):
self.cr.line_to(*NauticalSpeedometer.polar2xy(rspeed - s_middle, beta, x, y))
# short tick
- for n in xrange(10):
+ for n in range(10):
gamma = alpha + n * pi / 60
self.cr.move_to(*NauticalSpeedometer.polar2xy(rspeed, gamma, x, y))
self.cr.line_to(*NauticalSpeedometer.polar2xy(rspeed - s_short, gamma, x, y))
@@ -331,7 +331,7 @@ class NauticalSpeedometer(Speedometer):
self.cr.set_source_rgba(0, 0, 0)
# heading label 90/180/270
- for n in xrange(0, 4):
+ for n in range(0, 4):
label = str(n * 90)
# self.cr.set_source_rgba(0, 1, 0)
# radius * (1 + NauticalSpeedometer.HEADING_SAT_GAP),
@@ -367,7 +367,7 @@ class NauticalSpeedometer(Speedometer):
short_inset = self.short_inset(radius)
# draw the large ticks
- for i in xrange(12):
+ for i in range(12):
agllong = i * pi / 6
self.cr.move_to(*NauticalSpeedometer.polar2xy(radius - long_inset, agllong, x, y))
self.cr.line_to(*NauticalSpeedometer.polar2xy(radius, agllong, x, y))
@@ -381,7 +381,7 @@ class NauticalSpeedometer(Speedometer):
self.cr.line_to(*NauticalSpeedometer.polar2xy(radius, aglmid, x, y))
# short tick
- for n in xrange(1, 10):
+ for n in range(1, 10):
aglshrt = agllong + n * pi / 60
self.cr.move_to(*NauticalSpeedometer.polar2xy(radius - short_inset, aglshrt, x, y))
self.cr.line_to(*NauticalSpeedometer.polar2xy(radius, aglshrt, x, y))