Skip to content

Commit

Permalink
Merge pull request google#457 from jarondl/print
Browse files Browse the repository at this point in the history
Change print statements to functions for Python compatibility
  • Loading branch information
stotala committed Feb 10, 2019
2 parents 03e8ebf + 14ee635 commit 23038a9
Show file tree
Hide file tree
Showing 23 changed files with 118 additions and 95 deletions.
15 changes: 8 additions & 7 deletions examples/filter_unused_stops.py
Expand Up @@ -16,6 +16,7 @@


"""Filter the unused stops out of a transit feed file."""
from __future__ import print_function

import optparse
import sys
Expand All @@ -32,29 +33,29 @@ 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]

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)

Expand Down
5 changes: 3 additions & 2 deletions examples/google_random_queries.py
Expand Up @@ -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
Expand Down Expand Up @@ -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]

Expand Down
5 changes: 3 additions & 2 deletions examples/table.py
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down
17 changes: 9 additions & 8 deletions feedvalidator.py
Expand Up @@ -19,6 +19,7 @@
For usage information run feedvalidator.py --help
"""
from __future__ import print_function

import bisect
import codecs
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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=\
Expand All @@ -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


Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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')
Expand Down
3 changes: 2 additions & 1 deletion gtfsscheduleviewer/marey_graph.py
Expand Up @@ -32,6 +32,7 @@
and draws marey graphs in svg/xml format on request.
"""
from __future__ import print_function

import itertools
import transitfeed
Expand Down Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion kmlparser.py
Expand Up @@ -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
Expand Down Expand Up @@ -160,7 +161,7 @@ def main():
parser.Parse(args[0], feed)
feed.WriteGoogleTransitFeed(args[1])

print "Done."
print("Done.")


if __name__ == '__main__':
Expand Down
7 changes: 4 additions & 3 deletions kmlwriter.py
Expand Up @@ -68,6 +68,7 @@
- Routes - Rail
- Shapes
"""
from __future__ import print_function

try:
import xml.etree.ElementTree as ET # python 2.5
Expand Down Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions location_editor.py
Expand Up @@ -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

Expand All @@ -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):
Expand All @@ -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):
Expand Down
19 changes: 10 additions & 9 deletions merge.py
Expand Up @@ -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)'
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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):
Expand Down
11 changes: 6 additions & 5 deletions misc/find_pytz_transition_times.py
Expand Up @@ -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
Expand Down Expand Up @@ -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 = []
Expand Down Expand Up @@ -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)
13 changes: 7 additions & 6 deletions misc/import_ch_zurich.py
Expand Up @@ -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
Expand Down Expand Up @@ -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."
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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__':
Expand Down

0 comments on commit 23038a9

Please sign in to comment.