diff --git a/examples/filter_unused_stops.py b/examples/filter_unused_stops.py index 565ce8af..461597c2 100755 --- a/examples/filter_unused_stops.py +++ b/examples/filter_unused_stops.py @@ -16,6 +16,7 @@ """Filter the unused stops out of a transit feed file.""" +from __future__ import print_function import optparse import sys @@ -32,8 +33,8 @@ def main(): help="Print removed stops to stdout") (options, args) = parser.parse_args() if len(args) != 2: - print >>sys.stderr, parser.format_help() - print >>sys.stderr, "\n\nYou must provide input_feed and output_feed\n\n" + print(parser.format_help(), file=sys.stderr) + print("\n\nYou must provide input_feed and output_feed\n\n", file=sys.stderr) sys.exit(2) input_path = args[0] output_path = args[1] @@ -41,20 +42,20 @@ def main(): loader = transitfeed.Loader(input_path) schedule = loader.Load() - print "Removing unused stops..." + print("Removing unused stops...") removed = 0 for stop_id, stop in schedule.stops.items(): if not stop.GetTrips(schedule): removed += 1 del schedule.stops[stop_id] if options.list_removed: - print "Removing %s (%s)" % (stop_id, stop.stop_name) + print("Removing %s (%s)" % (stop_id, stop.stop_name)) if removed == 0: - print "No unused stops." + print("No unused stops.") elif removed == 1: - print "Removed 1 stop" + print("Removed 1 stop") else: - print "Removed %d stops" % removed + print("Removed %d stops" % removed) schedule.WriteGoogleTransitFeed(output_path) diff --git a/examples/google_random_queries.py b/examples/google_random_queries.py index 9128295a..72928381 100755 --- a/examples/google_random_queries.py +++ b/examples/google_random_queries.py @@ -23,6 +23,7 @@ look at the time of each leg. Also check the route names and headsigns are formatted correctly and not redundant. """ +from __future__ import print_function from datetime import datetime from datetime import timedelta @@ -209,8 +210,8 @@ def main(): parser.set_defaults(output="google_random_queries.html", limit=50) (options, args) = parser.parse_args() if len(args) != 1: - print >>sys.stderr, parser.format_help() - print >>sys.stderr, "\n\nYou must provide the path of a single feed\n\n" + print(parser.format_help(), file=sys.stderr) + print("\n\nYou must provide the path of a single feed\n\n", file=sys.stderr) sys.exit(2) feed_path = args[0] diff --git a/examples/table.py b/examples/table.py index eecc9ed7..ecd69376 100755 --- a/examples/table.py +++ b/examples/table.py @@ -32,6 +32,7 @@ # This is very simple example which you could use as a base for your own # transit feed builder. +from __future__ import print_function import transitfeed from optparse import OptionParser import re @@ -49,7 +50,7 @@ def AddRouteToSchedule(schedule, table): r = schedule.AddRoute(short_name=table[0][0], long_name=table[0][1], route_type='Bus') for trip in table[2:]: if len(trip) > len(table[1]): - print "ignoring %s" % trip[len(table[1]):] + print("ignoring %s" % trip[len(table[1]):]) trip = trip[0:len(table[1])] t = r.AddTrip(schedule, headsign='My headsign') trip_stops = [] # Build a list of (time, stopname) tuples @@ -112,7 +113,7 @@ def ProcessOptions(schedule, table): agency_timezone = row[1] if not (agency_name and agency_url and agency_timezone): - print "You must provide agency information" + print("You must provide agency information") schedule.NewDefaultAgency(agency_name=agency_name, agency_url=agency_url, agency_timezone=agency_timezone) diff --git a/feedvalidator.py b/feedvalidator.py index 1d265859..06de811e 100755 --- a/feedvalidator.py +++ b/feedvalidator.py @@ -19,6 +19,7 @@ For usage information run feedvalidator.py --help """ +from __future__ import print_function import bisect import codecs @@ -514,7 +515,7 @@ def RunValidationOutputToFilename(feed, options, output_filename): exit_code = RunValidationOutputToFile(feed, options, output_file) output_file.close() except IOError as e: - print 'Error while writing %s: %s' % (output_filename, e) + print('Error while writing %s: %s' % (output_filename, e)) output_filename = None exit_code = 2 @@ -579,8 +580,8 @@ def RunValidation(feed, options, problems): gtfs_factory = extension_module.GetGtfsFactory() - print 'validating %s' % feed - print 'FeedValidator extension used: %s' % options.extension + print('validating %s' % feed) + print('FeedValidator extension used: %s' % options.extension) loader = gtfs_factory.Loader(feed, problems=problems, extra_validation=False, memory_db=options.memory_db, check_duplicate_trips=\ @@ -597,10 +598,10 @@ def RunValidation(feed, options, problems): accumulator = problems.GetAccumulator() if accumulator.HasIssues(): - print 'ERROR: %s found' % accumulator.FormatCount() + print('ERROR: %s found' % accumulator.FormatCount()) return schedule, 1 else: - print 'feed validated successfully' + print('feed validated successfully') return schedule, 0 @@ -715,9 +716,9 @@ def ProfileRunValidationOutputFromOptions(feed, options): # Only available on Unix, http://docs.python.org/lib/module-resource.html import resource - print "Time: %d seconds" % ( + print("Time: %d seconds" % ( resource.getrusage(resource.RUSAGE_SELF).ru_utime + - resource.getrusage(resource.RUSAGE_SELF).ru_stime) + resource.getrusage(resource.RUSAGE_SELF).ru_stime)) # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286222 # http://aspn.activestate.com/ASPN/Cookbook/ "The recipes are freely @@ -751,7 +752,7 @@ def _VmB(VmKey): # I ran this on over a hundred GTFS files, comparing VmSize to VmRSS # (resident set size). The difference was always under 2% or 3MB. - print "Virtual Memory Size: %d bytes" % _VmB('VmSize:') + print("Virtual Memory Size: %d bytes" % _VmB('VmSize:')) # Output report of where CPU time was spent. p = pstats.Stats('validate-stats') diff --git a/gtfsscheduleviewer/marey_graph.py b/gtfsscheduleviewer/marey_graph.py index d3c82d51..81136965 100644 --- a/gtfsscheduleviewer/marey_graph.py +++ b/gtfsscheduleviewer/marey_graph.py @@ -32,6 +32,7 @@ and draws marey graphs in svg/xml format on request. """ +from __future__ import print_function import itertools import transitfeed @@ -292,7 +293,7 @@ def DistanceInTravelTime(dep_secs, arr_secs): return t_dists2 def _AddWarning(self, str): - print str + print(str) def _DrawTrips(self,triplist,colpar=""): """Generates svg polylines for each transit trip. diff --git a/kmlparser.py b/kmlparser.py index 93beb95f..993a8523 100755 --- a/kmlparser.py +++ b/kmlparser.py @@ -27,6 +27,7 @@ For line geometries, information about shapes is extracted from a kml file. """ +from __future__ import print_function import re import string @@ -160,7 +161,7 @@ def main(): parser.Parse(args[0], feed) feed.WriteGoogleTransitFeed(args[1]) - print "Done." + print("Done.") if __name__ == '__main__': diff --git a/kmlwriter.py b/kmlwriter.py index 4c413abe..34163d9b 100755 --- a/kmlwriter.py +++ b/kmlwriter.py @@ -68,6 +68,7 @@ - Routes - Rail - Shapes """ +from __future__ import print_function try: import xml.etree.ElementTree as ET # python 2.5 @@ -791,15 +792,15 @@ def main(): loader = transitfeed.Loader(input_path) feed = loader.Load() except transitfeed.ExceptionWithContext as e: - print >>sys.stderr, ( + print(( "\n\nGTFS feed must load without any errors.\n" "While loading %s the following error was found:\n%s\n%s\n" % (input_path, e.FormatContext(), - transitfeed.EncodeUnicode(e.FormatProblem()))) + transitfeed.EncodeUnicode(e.FormatProblem()))), file=sys.stderr) sys.exit(1) - print "Writing %s" % output_path + print("Writing %s" % output_path) writer = KMLWriter() writer.show_trips = options.show_trips writer.altitude_per_sec = options.altitude_per_sec diff --git a/location_editor.py b/location_editor.py index 96ef25ee..e3833bcc 100755 --- a/location_editor.py +++ b/location_editor.py @@ -22,6 +22,7 @@ # Usage: # location_editor.py --key `cat key` --port 8765 --feed_filename feed.zip +from __future__ import print_function import schedule_viewer import transitfeed @@ -39,7 +40,7 @@ def handle_json_GET_setstoplocation(self, params): stop.stop_lon = float(lon) msg = 'Location of ' + stop['stop_name'] + '(' + stop_id + ') set to ' + \ lat + 'x' + lon - print msg + print(msg) return msg def handle_json_GET_savedata(self, params): @@ -49,7 +50,7 @@ def handle_json_GET_savedata(self, params): else: schedule.WriteGoogleTransitFeed(self.server.feed_path) msg = 'Data saved to ' + self.server.feed_path - print msg + print(msg) return msg def AllowEditMode(self): diff --git a/merge.py b/merge.py index d900676d..0991096d 100755 --- a/merge.py +++ b/merge.py @@ -36,6 +36,7 @@ Run merge.py --help for a list of the possible options. """ +from __future__ import print_function __author__ = 'timothy.stranex@gmail.com (Timothy Stranex)' @@ -359,10 +360,10 @@ def LoadWithoutErrors(path, memory_db): problems=loading_problem_handler, extra_validation=True).Load() except transitfeed.ExceptionWithContext as e: - print >>sys.stderr, ( + print(( "\n\nFeeds to merge must load without any errors.\n" "While loading %s the following error was found:\n%s\n%s\n" % - (path, e.FormatContext(), transitfeed.EncodeUnicode(e.FormatProblem()))) + (path, e.FormatContext(), transitfeed.EncodeUnicode(e.FormatProblem()))), file=sys.stderr) sys.exit(1) return schedule @@ -1004,10 +1005,10 @@ def MergeDataSets(self): self._UpdateAndMigrateUnmerged(self._b_not_merged, fm.b_zone_map, fm.b_merge_map, fm.b_schedule) - print 'Stops merged: %d of %d, %d' % ( + print('Stops merged: %d of %d, %d' % ( num_merged, len(fm.a_schedule.GetStopList()), - len(fm.b_schedule.GetStopList())) + len(fm.b_schedule.GetStopList()))) return True def _UpdateAndMigrateUnmerged(self, not_merged_stops, zone_map, merge_map, @@ -1271,10 +1272,10 @@ def _GetId(self, fare): def MergeDataSets(self): num_merged = self._MergeSameId() - print 'Fares merged: %d of %d, %d' % ( + print('Fares merged: %d of %d, %d' % ( num_merged, len(self.feed_merger.a_schedule.GetFareAttributeList()), - len(self.feed_merger.b_schedule.GetFareAttributeList())) + len(self.feed_merger.b_schedule.GetFareAttributeList()))) return True @@ -1319,12 +1320,12 @@ def MergeDataSets(self): # to_stop_id but different transfer_type or min_transfer_time only the # transfer from b will be in the output. self._MergeByIdKeepNew() - print 'Transfers merged: %d of %d, %d' % ( + print('Transfers merged: %d of %d, %d' % ( self._num_merged, # http://mail.python.org/pipermail/baypiggies/2008-August/003817.html # claims this is a good way to find number of items in an iterable. sum(1 for _ in self.feed_merger.a_schedule.GetTransferIter()), - sum(1 for _ in self.feed_merger.b_schedule.GetTransferIter())) + sum(1 for _ in self.feed_merger.b_schedule.GetTransferIter()))) return True @@ -1542,7 +1543,7 @@ def MergeDataSets(self): if rules: self.feed_merger.problem_reporter.FareRulesBroken(self) - print 'Fare Rules: union has %d fare rules' % len(rules) + print('Fare Rules: union has %d fare rules' % len(rules)) return True def GetMergeStats(self): diff --git a/misc/find_pytz_transition_times.py b/misc/find_pytz_transition_times.py index 13c90be5..29522c9f 100644 --- a/misc/find_pytz_transition_times.py +++ b/misc/find_pytz_transition_times.py @@ -22,6 +22,7 @@ This script depends on internals of pytz. I considered hacking up something based on zic.c or zdump.c in tzcode2009k.tar.gz but this seemed much easier. """ +from __future__ import print_function import pytz import datetime @@ -49,8 +50,8 @@ def show_tran(dist, tz_name, tran, inf): closest_tran_utc = pytz.utc.localize(tran) before = closest_tran_utc + datetime.timedelta(seconds=-1) after = closest_tran_utc + datetime.timedelta(seconds=1) - print "%d from %s to %s %s" % (dist, before.astimezone(tzinfo), - after.astimezone(tzinfo), tz_name) + print("%d from %s to %s %s" % (dist, before.astimezone(tzinfo), + after.astimezone(tzinfo), tz_name)) from_noon = [] from_midnight = [] @@ -83,15 +84,15 @@ def show_tran(dist, tz_name, tran, inf): distance_from_midnight = hour_dist(average, 0) from_midnight.append((distance_from_midnight, tz_name, tran, inf)) except Exception as e: - print "Trouble with %s %s %s: %s" % (tz_name, tran, inf, e) + print("Trouble with %s %s %s: %s" % (tz_name, tran, inf, e)) -print "Near noon" +print("Near noon") from_noon.sort() for t in from_noon[0:10]: show_tran(*t) -print "Near midnight" +print("Near midnight") from_midnight.sort() for t in from_midnight[0:30]: show_tran(*t) diff --git a/misc/import_ch_zurich.py b/misc/import_ch_zurich.py index 587227eb..5bb5352d 100755 --- a/misc/import_ch_zurich.py +++ b/misc/import_ch_zurich.py @@ -16,6 +16,7 @@ """Imports Zurich timetables, converting them from DIVA export format to Google Transit format.""" +from __future__ import print_function # This was written before transitfeed.py and we haven't yet found the # motivation to port it. Please see the examples directory for better @@ -225,8 +226,8 @@ def ImportStations(self, station_file, adv_file): # Line ids in this file have leading zeroes, remove. self.stations[station_id].advertised_lines.add(line_id.lstrip("0")) else: - print "Warning, advertised lines file references " \ - "unknown station, id " + station_id + print("Warning, advertised lines file references " \ + "unknown station, id " + station_id) def ImportRoutes(self, s): "Imports the rec_lin_ber.mdv file." @@ -360,8 +361,8 @@ def ImportTrips(self, trips_file): 'FGR_NR', 'FPL_KUERZEL', 'TAGESMERKMAL_NR', 'VB', 'FRT_HP_AUS', 'HALTEPUNKT_NR_ZIEL', 'FAHRTART_NR']): if trip_type != '1': - print "skipping Trip ", trip_id, line, direction, \ - dest_station_id, trip_type + print("skipping Trip ", trip_id, line, direction, \ + dest_station_id, trip_type) continue # 1=normal, 2=empty, 3=from depot, 4=to depot, 5=other trip = Trip() #The trip_id (FRT_FID) field is not unique in the vbz data, as of Dec 2009 @@ -442,7 +443,7 @@ def WriteTrips(self, out): trips.sort() for (trip_id, trip) in trips: if (not len(trip.pattern.stops)) or (None in trip.pattern.stops): - print "*** Skipping bad trip: ", [trip.id] + print("*** Skipping bad trip: ", [trip.id]) continue self.goodTrips[trip_id] = True headsign = self.stations[trip.pattern.stops[-1]].name @@ -502,7 +503,7 @@ def main(argv): importer = DivaImporter(ConvertCH1903, options.drop_unadvertised_lines) importer.Import(options.in_file) importer.Write(options.out_file) - print 'Wrote output to', options.out_file + print('Wrote output to', options.out_file) if __name__ == '__main__': diff --git a/misc/sql_loop.py b/misc/sql_loop.py index 4f1cec0e..0fb76c64 100755 --- a/misc/sql_loop.py +++ b/misc/sql_loop.py @@ -15,6 +15,7 @@ # limitations under the License. """Command line interface to an sqlite database, can also load a db from csv.""" +from __future__ import print_function import cmd @@ -42,10 +43,10 @@ def __init__(self, cursor): TURAL JOIN stops WHERE trip_headsign LIKE '%intern%' ORDER BY trip_id,time""" def do_help(self, topic): - print self.doc + print(self.doc) def do_EOF(self, line): - print + print() return True def default(self, line): @@ -62,11 +63,11 @@ def default(self, line): self.cursor.execute(line); s = "%s" % self.cursor.fetchall() if len(s) > 2000: - print s[0:2000] + print(s[0:2000]) else: - print s + print(s) except sqlite.DatabaseError as e: - print "error %s" % e + print("error %s" % e) def LoadNamedFile(file_name, conn): @@ -101,13 +102,13 @@ def LoadFile(f, table_name, conn): c.execute("CREATE TABLE %s (%s)" % (table_name, ",".join(create_columns))) except sqlite.OperationalError: # Likely table exists - print "table %s already exists?" % (table_name) + print("table %s already exists?" % (table_name)) for create_column in create_columns: try: c.execute("ALTER TABLE %s ADD COLUMN %s" % (table_name, create_column)) except sqlite.OperationalError: # Likely it already exists - print "column %s already exists in %s?" % (create_column, table_name) + print("column %s already exists in %s?" % (create_column, table_name)) placeholders = ",".join(["?"] * len(columns)) insert_values = "INSERT INTO %s (%s) VALUES (%s)" % (table_name, ",".join(columns), placeholders) diff --git a/misc/traceplus.py b/misc/traceplus.py index 930c9ef3..c1bece48 100644 --- a/misc/traceplus.py +++ b/misc/traceplus.py @@ -19,6 +19,7 @@ See traceplus_example.py for a demonstration. """ +from __future__ import print_function def MakeExpandedTrace(frame_records): """Return a list of text lines for the given list of frame records.""" diff --git a/misc/traceplus_example.py b/misc/traceplus_example.py index 2c85d05e..7f5df2a6 100755 --- a/misc/traceplus_example.py +++ b/misc/traceplus_example.py @@ -1,5 +1,6 @@ #!/usr/bin/python3 +from __future__ import print_function import argparse parser = argparse.ArgumentParser() diff --git a/schedule_viewer.py b/schedule_viewer.py index 63ad6208..0ac217c5 100755 --- a/schedule_viewer.py +++ b/schedule_viewer.py @@ -19,6 +19,7 @@ You must provide a Google Maps API key. """ +from __future__ import print_function import BaseHTTPServer, sys, urlparse @@ -120,7 +121,7 @@ def do_GET(self): f, mime_type = self.OpenFile(m.group(1)) return self.handle_static_file_GET(f, mime_type) except IOError as e: - print "Error: unable to open %s" % m.group(1) + print("Error: unable to open %s" % m.group(1)) # Ignore and treat as 404 m = re.match(r'/([a-z]{1,64})', path) @@ -418,14 +419,14 @@ def handle_GET_ttablegraph(self,params): height = int(params.get('height', 300)) if not route: - print 'no such route' + print('no such route') self.send_error(404) return pattern_id_trip_dict = route.GetPatternIdTripDict() pattern_id = trip.pattern_id if pattern_id not in pattern_id_trip_dict: - print 'no pattern %s found in %s' % (pattern_id, pattern_id_trip_dict.keys()) + print('no pattern %s found in %s' % (pattern_id, pattern_id_trip_dict.keys())) self.send_error(404) return triplist = pattern_id_trip_dict[pattern_id] @@ -515,7 +516,7 @@ def main(RequestHandlerClass = ScheduleRequestHandler): (options, args) = parser.parse_args() if not os.path.isfile(os.path.join(options.file_dir, 'index.html')): - print "Can't find index.html with --file_dir=%s" % options.file_dir + print("Can't find index.html with --file_dir=%s" % options.file_dir) exit(1) if not options.feed_filename and len(args) == 1: @@ -538,8 +539,8 @@ def main(RequestHandlerClass = ScheduleRequestHandler): util.CheckVersion(transitfeed.ProblemReporter()) schedule = transitfeed.Schedule(problem_reporter=transitfeed.ProblemReporter()) - print 'Loading data from feed "%s"...' % options.feed_filename - print '(this may take a few minutes for larger cities)' + print('Loading data from feed "%s"...' % options.feed_filename) + print('(this may take a few minutes for larger cities)') schedule.Load(options.feed_filename) server = StoppableHTTPServer(server_address=('', options.port), diff --git a/shape_importer.py b/shape_importer.py index c66032b6..8c12f191 100755 --- a/shape_importer.py +++ b/shape_importer.py @@ -18,6 +18,7 @@ Requires the ogr python package. """ +from __future__ import print_function __author__ = 'chris.harrelson.code@gmail.com (Chris Harrelson)' @@ -48,10 +49,10 @@ def PrintColumns(shapefile): raise ShapeImporterError("Layer 0 has no elements!") feature = layer.GetFeature(0) - print "%d features" % feature.GetFieldCount() + print("%d features" % feature.GetFieldCount()) for j in range(0, feature.GetFieldCount()): - print '--' + feature.GetFieldDefnRef(j).GetName() + \ - ': ' + feature.GetFieldAsString(j) + print('--' + feature.GetFieldDefnRef(j).GetName() + \ + ': ' + feature.GetFieldAsString(j)) def AddShapefile(shapefile, graph, key_cols): @@ -96,7 +97,7 @@ def GetMatchingShape(pattern_poly, trip, matches, max_distance, verbosity=0): if verbosity >= 1: for match in matches: - print "match: size %d" % match.GetNumPoints() + print("match: size %d" % match.GetNumPoints()) scores = [(pattern_poly.GreedyPolyMatchDist(match), match) for match in matches] @@ -117,14 +118,14 @@ def AddExtraShapes(extra_shapes_txt, graph): a pain to edit .shp files. """ - print "Adding extra shapes from %s" % extra_shapes_txt + print("Adding extra shapes from %s" % extra_shapes_txt) try: tmpdir = tempfile.mkdtemp() shutil.copy(extra_shapes_txt, os.path.join(tmpdir, 'shapes.txt')) loader = transitfeed.ShapeLoader(tmpdir) schedule = loader.Load() for shape in schedule.GetShapeList(): - print "Adding extra shape: %s" % shape.shape_id + print("Adding extra shape: %s" % shape.shape_id) graph.AddPoly(ShapeToPoly(shape)) finally: if tmpdir: @@ -194,25 +195,25 @@ def DefineOptions(): def main(key_cols): - print 'Parsing shapefile(s)...' + print('Parsing shapefile(s)...') graph = shapelib.PolyGraph() for arg in args: - print ' ' + arg + print(' ' + arg) AddShapefile(arg, graph, key_cols) if options.extra_shapes: AddExtraShapes(options.extra_shapes, graph) - print 'Loading GTFS from %s...' % options.source_gtfs + print('Loading GTFS from %s...' % options.source_gtfs) schedule = transitfeed.Loader(options.source_gtfs).Load() shape_count = 0 pattern_count = 0 verbosity = options.verbosity - print 'Matching shapes to trips...' + print('Matching shapes to trips...') for route in schedule.GetRouteList(): - print 'Processing route', route.route_short_name + print('Processing route', route.route_short_name) patterns = route.GetPatternIdTripDict() for pattern_id, trips in patterns.iteritems(): pattern_count += 1 @@ -221,9 +222,9 @@ def main(key_cols): poly_points = [shapelib.Point.FromLatLng(p.stop_lat, p.stop_lon) for p in pattern] if verbosity >= 2: - print "\npattern %d, %d points:" % (pattern_id, len(poly_points)) + print("\npattern %d, %d points:" % (pattern_id, len(poly_points))) for i, (stop, point) in enumerate(zip(pattern, poly_points)): - print "Stop %d '%s': %s" % (i + 1, stop.stop_name, point.ToLatLng()) + print("Stop %d '%s': %s" % (i + 1, stop.stop_name, point.ToLatLng())) # First, try to find polys that run all the way from # the start of the trip to the end. @@ -263,7 +264,7 @@ def main(key_cols): schedule.AddShapeObject(shape) trip.shape_id = shape.shape_id - print "Matched %d shapes out of %d patterns" % (shape_count, pattern_count) + print("Matched %d shapes out of %d patterns" % (shape_count, pattern_count)) schedule.WriteGoogleTransitFeed(options.dest_gtfs) diff --git a/tests/testmerge.py b/tests/testmerge.py index 9068b895..1759d8ba 100644 --- a/tests/testmerge.py +++ b/tests/testmerge.py @@ -16,6 +16,7 @@ """Unit tests for the merge module.""" from __future__ import absolute_import +from __future__ import print_function __author__ = 'timothy.stranex@gmail.com (Timothy Stranex)' @@ -1545,7 +1546,7 @@ def testCheckVersionIsRun(self): future_good_feed, os.path.join(self.tempdirpath, 'merged.zip')], expected_retcode=0) - print out + print(out) htmlout = open('merge-results.html').read() self.assertTrue(re.search(r'A new version 100.100.100', htmlout)) diff --git a/tests/testshapelib.py b/tests/testshapelib.py index 30632e6f..2dfb316f 100644 --- a/tests/testshapelib.py +++ b/tests/testshapelib.py @@ -16,6 +16,7 @@ """Tests for transitfeed.shapelib.py""" from __future__ import absolute_import +from __future__ import print_function __author__ = 'chris.harrelson.code@gmail.com (Chris Harrelson)' @@ -48,14 +49,14 @@ def assertPointApproxEq(self, a, b): self.assertApproxEq(a.y, b.y) self.assertApproxEq(a.z, b.z) except AssertionError: - print 'ERROR: %s != %s' % (formatPoint(a), formatPoint(b)) + print('ERROR: %s != %s' % (formatPoint(a), formatPoint(b))) raise def assertPointsApproxEq(self, points1, points2): try: self.assertEqual(len(points1), len(points2)) except AssertionError: - print "ERROR: %s != %s" % (formatPoints(points1), formatPoints(points2)) + print("ERROR: %s != %s" % (formatPoints(points1), formatPoints(points2))) raise for i in xrange(len(points1)): try: diff --git a/tests/util.py b/tests/util.py index 452d2007..5e725288 100644 --- a/tests/util.py +++ b/tests/util.py @@ -16,6 +16,7 @@ # Code shared between tests. from __future__ import absolute_import +from __future__ import print_function import dircache import os @@ -329,7 +330,7 @@ def DumpZipFile(self, zf): # Handy for debugging z = zipfile.ZipFile(zf) for n in z.namelist(): - print "--\n%s\n%s" % (n, z.read(n)) + print("--\n%s\n%s" % (n, z.read(n))) class LoadTestCase(TestCase): diff --git a/transitfeed/problems.py b/transitfeed/problems.py index 1edad137..a1a96375 100755 --- a/transitfeed/problems.py +++ b/transitfeed/problems.py @@ -14,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +from __future__ import print_function import logging import time @@ -378,8 +379,8 @@ class SimpleProblemAccumulator(ProblemAccumulatorInterface): def _Report(self, e): context = e.FormatContext() if context: - print context - print util.EncodeUnicode(self._LineWrap(e.FormatProblem(), 78)) + print(context) + print(util.EncodeUnicode(self._LineWrap(e.FormatProblem(), 78))) @staticmethod def _LineWrap(text, width): diff --git a/transitfeed/shapelib.py b/transitfeed/shapelib.py index 744b81d1..5d6003bf 100644 --- a/transitfeed/shapelib.py +++ b/transitfeed/shapelib.py @@ -28,6 +28,7 @@ is adequate; for other purposes, this library may not be accurate enough. """ +from __future__ import print_function __author__ = 'chris.harrelson.code@gmail.com (Chris Harrelson)' @@ -400,9 +401,9 @@ def AddPoly(self, poly, smart_duplicate_handling=True): print ("Warning: duplicate shape id being added to collection: " + poly.GetName()) if poly.GreedyPolyMatchDist(self._name_to_shape[poly.GetName()]) < 10: - print " (Skipping as it apears to be an exact duplicate)" + print(" (Skipping as it apears to be an exact duplicate)") else: - print " (Adding new shape variant with uniquified name)" + print(" (Adding new shape variant with uniquified name)") inserted_name = "%s-%d" % (inserted_name, len(self._name_to_shape)) self._name_to_shape[inserted_name] = poly @@ -549,7 +550,7 @@ def FindShortestMultiPointPath(self, points, max_radius=150, keep_best_n=10, if nearby: nearby_points.append(nearby) else: - print "No nearby points found for point %s" % str(point.ToLatLng()) + print("No nearby points found for point %s" % str(point.ToLatLng())) return None pathToStr = lambda start, end, path: (" Best path %s -> %s: %s" @@ -558,7 +559,7 @@ def FindShortestMultiPointPath(self, points, max_radius=150, keep_best_n=10, path and path.GetName() or "None")) if verbosity >= 3: - print "Step 1" + print("Step 1") step = 2 start_points = nearby_points[0] @@ -568,12 +569,12 @@ def FindShortestMultiPointPath(self, points, max_radius=150, keep_best_n=10, for end in end_points: path = self.ShortestPath(start, end) if verbosity >= 3: - print pathToStr(start, end, path) + print(pathToStr(start, end, path)) PolyGraph._AddPathToHeap(paths_found, path, keep_best_n) for possible_points in nearby_points[2:]: if verbosity >= 3: - print "\nStep %d" % step + print("\nStep %d" % step) step += 1 new_paths_found = [] @@ -586,7 +587,7 @@ def FindShortestMultiPointPath(self, points, max_radius=150, keep_best_n=10, else: new_segment = self.ShortestPath(start, end) if verbosity >= 3: - print pathToStr(start, end, new_segment) + print(pathToStr(start, end, new_segment)) start_end_paths[(start, end)] = new_segment if new_segment: diff --git a/transitfeed/util.py b/transitfeed/util.py index f96cae09..aff80c39 100644 --- a/transitfeed/util.py +++ b/transitfeed/util.py @@ -14,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +from __future__ import print_function import codecs import csv import datetime @@ -37,8 +38,8 @@ class OptionParserLongError(optparse.OptionParser): """OptionParser subclass that includes list of options above error message.""" def error(self, msg): - print >>sys.stderr, self.format_help() - print >>sys.stderr, '\n\n%s: error: %s\n\n' % (self.get_prog_name(), msg) + print(self.format_help(), file=sys.stderr) + print('\n\n%s: error: %s\n\n' % (self.get_prog_name(), msg), file=sys.stderr) sys.exit(2) @@ -103,10 +104,10 @@ def RunWithCrashHandler(f): open('transitfeedcrash.txt', 'w').write(''.join(dump)) - print ''.join(dump) - print - print dashes - print apology + print(''.join(dump)) + print() + print(dashes) + print(apology) try: raw_input('Press enter to continue...') @@ -557,7 +558,7 @@ def writerow(self, row): try: self.writer.writerow(encoded_row) except Exception as e: - print 'error writing %s as %s' % (row, encoded_row) + print('error writing %s as %s' % (row, encoded_row)) raise e def writerows(self, rows): diff --git a/unusual_trip_filter.py b/unusual_trip_filter.py index b12e45c4..c0c22101 100644 --- a/unusual_trip_filter.py +++ b/unusual_trip_filter.py @@ -20,6 +20,7 @@ For usage information run unusual_trip_filter.py --help """ +from __future__ import print_function __author__ = 'Jiri Semecky ' @@ -96,7 +97,7 @@ def filter(self, dataset): def info(self, text): if not self._quiet: - print text.encode("utf-8") + print(text.encode("utf-8")) def main(): @@ -146,7 +147,7 @@ def main(): memory_db=options.memory_db) data = loader.Load() filter.filter(data) - print 'Saving data' + print('Saving data') # Write the result if options.output is None: