Skip to content
This repository was archived by the owner on Nov 30, 2023. It is now read-only.

Commit 70ab424

Browse files
committed
change print statements to functions for Python compatibility
Another backwards compatible change as part of #412 by running: futurize -nw -f libfuturize.fixes.fix_print_with_import .
1 parent 54a4081 commit 70ab424

23 files changed

+118
-95
lines changed

examples/filter_unused_stops.py

+8-7
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717

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

2021
import optparse
2122
import sys
@@ -32,29 +33,29 @@ def main():
3233
help="Print removed stops to stdout")
3334
(options, args) = parser.parse_args()
3435
if len(args) != 2:
35-
print >>sys.stderr, parser.format_help()
36-
print >>sys.stderr, "\n\nYou must provide input_feed and output_feed\n\n"
36+
print(parser.format_help(), file=sys.stderr)
37+
print("\n\nYou must provide input_feed and output_feed\n\n", file=sys.stderr)
3738
sys.exit(2)
3839
input_path = args[0]
3940
output_path = args[1]
4041

4142
loader = transitfeed.Loader(input_path)
4243
schedule = loader.Load()
4344

44-
print "Removing unused stops..."
45+
print("Removing unused stops...")
4546
removed = 0
4647
for stop_id, stop in schedule.stops.items():
4748
if not stop.GetTrips(schedule):
4849
removed += 1
4950
del schedule.stops[stop_id]
5051
if options.list_removed:
51-
print "Removing %s (%s)" % (stop_id, stop.stop_name)
52+
print("Removing %s (%s)" % (stop_id, stop.stop_name))
5253
if removed == 0:
53-
print "No unused stops."
54+
print("No unused stops.")
5455
elif removed == 1:
55-
print "Removed 1 stop"
56+
print("Removed 1 stop")
5657
else:
57-
print "Removed %d stops" % removed
58+
print("Removed %d stops" % removed)
5859

5960
schedule.WriteGoogleTransitFeed(output_path)
6061

examples/google_random_queries.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
look at the time of each leg. Also check the route names and headsigns are
2424
formatted correctly and not redundant.
2525
"""
26+
from __future__ import print_function
2627

2728
from datetime import datetime
2829
from datetime import timedelta
@@ -209,8 +210,8 @@ def main():
209210
parser.set_defaults(output="google_random_queries.html", limit=50)
210211
(options, args) = parser.parse_args()
211212
if len(args) != 1:
212-
print >>sys.stderr, parser.format_help()
213-
print >>sys.stderr, "\n\nYou must provide the path of a single feed\n\n"
213+
print(parser.format_help(), file=sys.stderr)
214+
print("\n\nYou must provide the path of a single feed\n\n", file=sys.stderr)
214215
sys.exit(2)
215216
feed_path = args[0]
216217

examples/table.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
# This is very simple example which you could use as a base for your own
3333
# transit feed builder.
3434

35+
from __future__ import print_function
3536
import transitfeed
3637
from optparse import OptionParser
3738
import re
@@ -49,7 +50,7 @@ def AddRouteToSchedule(schedule, table):
4950
r = schedule.AddRoute(short_name=table[0][0], long_name=table[0][1], route_type='Bus')
5051
for trip in table[2:]:
5152
if len(trip) > len(table[1]):
52-
print "ignoring %s" % trip[len(table[1]):]
53+
print("ignoring %s" % trip[len(table[1]):])
5354
trip = trip[0:len(table[1])]
5455
t = r.AddTrip(schedule, headsign='My headsign')
5556
trip_stops = [] # Build a list of (time, stopname) tuples
@@ -112,7 +113,7 @@ def ProcessOptions(schedule, table):
112113
agency_timezone = row[1]
113114

114115
if not (agency_name and agency_url and agency_timezone):
115-
print "You must provide agency information"
116+
print("You must provide agency information")
116117

117118
schedule.NewDefaultAgency(agency_name=agency_name, agency_url=agency_url,
118119
agency_timezone=agency_timezone)

feedvalidator.py

+9-8
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
2020
For usage information run feedvalidator.py --help
2121
"""
22+
from __future__ import print_function
2223

2324
import bisect
2425
import codecs
@@ -514,7 +515,7 @@ def RunValidationOutputToFilename(feed, options, output_filename):
514515
exit_code = RunValidationOutputToFile(feed, options, output_file)
515516
output_file.close()
516517
except IOError, e:
517-
print 'Error while writing %s: %s' % (output_filename, e)
518+
print('Error while writing %s: %s' % (output_filename, e))
518519
output_filename = None
519520
exit_code = 2
520521

@@ -579,8 +580,8 @@ def RunValidation(feed, options, problems):
579580

580581
gtfs_factory = extension_module.GetGtfsFactory()
581582

582-
print 'validating %s' % feed
583-
print 'FeedValidator extension used: %s' % options.extension
583+
print('validating %s' % feed)
584+
print('FeedValidator extension used: %s' % options.extension)
584585
loader = gtfs_factory.Loader(feed, problems=problems, extra_validation=False,
585586
memory_db=options.memory_db,
586587
check_duplicate_trips=\
@@ -597,10 +598,10 @@ def RunValidation(feed, options, problems):
597598

598599
accumulator = problems.GetAccumulator()
599600
if accumulator.HasIssues():
600-
print 'ERROR: %s found' % accumulator.FormatCount()
601+
print('ERROR: %s found' % accumulator.FormatCount())
601602
return schedule, 1
602603
else:
603-
print 'feed validated successfully'
604+
print('feed validated successfully')
604605
return schedule, 0
605606

606607

@@ -715,9 +716,9 @@ def ProfileRunValidationOutputFromOptions(feed, options):
715716

716717
# Only available on Unix, http://docs.python.org/lib/module-resource.html
717718
import resource
718-
print "Time: %d seconds" % (
719+
print("Time: %d seconds" % (
719720
resource.getrusage(resource.RUSAGE_SELF).ru_utime +
720-
resource.getrusage(resource.RUSAGE_SELF).ru_stime)
721+
resource.getrusage(resource.RUSAGE_SELF).ru_stime))
721722

722723
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286222
723724
# http://aspn.activestate.com/ASPN/Cookbook/ "The recipes are freely
@@ -751,7 +752,7 @@ def _VmB(VmKey):
751752

752753
# I ran this on over a hundred GTFS files, comparing VmSize to VmRSS
753754
# (resident set size). The difference was always under 2% or 3MB.
754-
print "Virtual Memory Size: %d bytes" % _VmB('VmSize:')
755+
print("Virtual Memory Size: %d bytes" % _VmB('VmSize:'))
755756

756757
# Output report of where CPU time was spent.
757758
p = pstats.Stats('validate-stats')

gtfsscheduleviewer/marey_graph.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
and draws marey graphs in svg/xml format on request.
3333
3434
"""
35+
from __future__ import print_function
3536

3637
import itertools
3738
import transitfeed
@@ -292,7 +293,7 @@ def DistanceInTravelTime(dep_secs, arr_secs):
292293
return t_dists2
293294

294295
def _AddWarning(self, str):
295-
print str
296+
print(str)
296297

297298
def _DrawTrips(self,triplist,colpar=""):
298299
"""Generates svg polylines for each transit trip.

kmlparser.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
For line geometries, information about shapes is extracted from a kml file.
2828
2929
"""
30+
from __future__ import print_function
3031

3132
import re
3233
import string
@@ -160,7 +161,7 @@ def main():
160161
parser.Parse(args[0], feed)
161162
feed.WriteGoogleTransitFeed(args[1])
162163

163-
print "Done."
164+
print("Done.")
164165

165166

166167
if __name__ == '__main__':

kmlwriter.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
- Routes - Rail
6969
- Shapes
7070
"""
71+
from __future__ import print_function
7172

7273
try:
7374
import xml.etree.ElementTree as ET # python 2.5
@@ -791,15 +792,15 @@ def main():
791792
loader = transitfeed.Loader(input_path)
792793
feed = loader.Load()
793794
except transitfeed.ExceptionWithContext, e:
794-
print >>sys.stderr, (
795+
print((
795796
"\n\nGTFS feed must load without any errors.\n"
796797
"While loading %s the following error was found:\n%s\n%s\n" %
797798
(input_path,
798799
e.FormatContext(),
799-
transitfeed.EncodeUnicode(e.FormatProblem())))
800+
transitfeed.EncodeUnicode(e.FormatProblem()))), file=sys.stderr)
800801
sys.exit(1)
801802

802-
print "Writing %s" % output_path
803+
print("Writing %s" % output_path)
803804
writer = KMLWriter()
804805
writer.show_trips = options.show_trips
805806
writer.altitude_per_sec = options.altitude_per_sec

location_editor.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
# Usage:
2323
# location_editor.py --key `cat key` --port 8765 --feed_filename feed.zip
2424

25+
from __future__ import print_function
2526
import schedule_viewer
2627
import transitfeed
2728

@@ -39,7 +40,7 @@ def handle_json_GET_setstoplocation(self, params):
3940
stop.stop_lon = float(lon)
4041
msg = 'Location of ' + stop['stop_name'] + '(' + stop_id + ') set to ' + \
4142
lat + 'x' + lon
42-
print msg
43+
print(msg)
4344
return msg
4445

4546
def handle_json_GET_savedata(self, params):
@@ -49,7 +50,7 @@ def handle_json_GET_savedata(self, params):
4950
else:
5051
schedule.WriteGoogleTransitFeed(self.server.feed_path)
5152
msg = 'Data saved to ' + self.server.feed_path
52-
print msg
53+
print(msg)
5354
return msg
5455

5556
def AllowEditMode(self):

merge.py

+10-9
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
3737
Run merge.py --help for a list of the possible options.
3838
"""
39+
from __future__ import print_function
3940

4041

4142
__author__ = '[email protected] (Timothy Stranex)'
@@ -359,10 +360,10 @@ def LoadWithoutErrors(path, memory_db):
359360
problems=loading_problem_handler,
360361
extra_validation=True).Load()
361362
except transitfeed.ExceptionWithContext, e:
362-
print >>sys.stderr, (
363+
print((
363364
"\n\nFeeds to merge must load without any errors.\n"
364365
"While loading %s the following error was found:\n%s\n%s\n" %
365-
(path, e.FormatContext(), transitfeed.EncodeUnicode(e.FormatProblem())))
366+
(path, e.FormatContext(), transitfeed.EncodeUnicode(e.FormatProblem()))), file=sys.stderr)
366367
sys.exit(1)
367368
return schedule
368369

@@ -1004,10 +1005,10 @@ def MergeDataSets(self):
10041005
self._UpdateAndMigrateUnmerged(self._b_not_merged, fm.b_zone_map,
10051006
fm.b_merge_map, fm.b_schedule)
10061007

1007-
print 'Stops merged: %d of %d, %d' % (
1008+
print('Stops merged: %d of %d, %d' % (
10081009
num_merged,
10091010
len(fm.a_schedule.GetStopList()),
1010-
len(fm.b_schedule.GetStopList()))
1011+
len(fm.b_schedule.GetStopList())))
10111012
return True
10121013

10131014
def _UpdateAndMigrateUnmerged(self, not_merged_stops, zone_map, merge_map,
@@ -1271,10 +1272,10 @@ def _GetId(self, fare):
12711272

12721273
def MergeDataSets(self):
12731274
num_merged = self._MergeSameId()
1274-
print 'Fares merged: %d of %d, %d' % (
1275+
print('Fares merged: %d of %d, %d' % (
12751276
num_merged,
12761277
len(self.feed_merger.a_schedule.GetFareAttributeList()),
1277-
len(self.feed_merger.b_schedule.GetFareAttributeList()))
1278+
len(self.feed_merger.b_schedule.GetFareAttributeList())))
12781279
return True
12791280

12801281

@@ -1319,12 +1320,12 @@ def MergeDataSets(self):
13191320
# to_stop_id but different transfer_type or min_transfer_time only the
13201321
# transfer from b will be in the output.
13211322
self._MergeByIdKeepNew()
1322-
print 'Transfers merged: %d of %d, %d' % (
1323+
print('Transfers merged: %d of %d, %d' % (
13231324
self._num_merged,
13241325
# http://mail.python.org/pipermail/baypiggies/2008-August/003817.html
13251326
# claims this is a good way to find number of items in an iterable.
13261327
sum(1 for _ in self.feed_merger.a_schedule.GetTransferIter()),
1327-
sum(1 for _ in self.feed_merger.b_schedule.GetTransferIter()))
1328+
sum(1 for _ in self.feed_merger.b_schedule.GetTransferIter())))
13281329
return True
13291330

13301331

@@ -1542,7 +1543,7 @@ def MergeDataSets(self):
15421543

15431544
if rules:
15441545
self.feed_merger.problem_reporter.FareRulesBroken(self)
1545-
print 'Fare Rules: union has %d fare rules' % len(rules)
1546+
print('Fare Rules: union has %d fare rules' % len(rules))
15461547
return True
15471548

15481549
def GetMergeStats(self):

misc/find_pytz_transition_times.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
This script depends on internals of pytz. I considered hacking up something
2323
based on zic.c or zdump.c in tzcode2009k.tar.gz but this seemed much easier.
2424
"""
25+
from __future__ import print_function
2526

2627
import pytz
2728
import datetime
@@ -49,8 +50,8 @@ def show_tran(dist, tz_name, tran, inf):
4950
closest_tran_utc = pytz.utc.localize(tran)
5051
before = closest_tran_utc + datetime.timedelta(seconds=-1)
5152
after = closest_tran_utc + datetime.timedelta(seconds=1)
52-
print "%d from %s to %s %s" % (dist, before.astimezone(tzinfo),
53-
after.astimezone(tzinfo), tz_name)
53+
print("%d from %s to %s %s" % (dist, before.astimezone(tzinfo),
54+
after.astimezone(tzinfo), tz_name))
5455

5556
from_noon = []
5657
from_midnight = []
@@ -83,15 +84,15 @@ def show_tran(dist, tz_name, tran, inf):
8384
distance_from_midnight = hour_dist(average, 0)
8485
from_midnight.append((distance_from_midnight, tz_name, tran, inf))
8586
except Exception, e:
86-
print "Trouble with %s %s %s: %s" % (tz_name, tran, inf, e)
87+
print("Trouble with %s %s %s: %s" % (tz_name, tran, inf, e))
8788

8889

89-
print "Near noon"
90+
print("Near noon")
9091
from_noon.sort()
9192
for t in from_noon[0:10]:
9293
show_tran(*t)
9394

94-
print "Near midnight"
95+
print("Near midnight")
9596
from_midnight.sort()
9697
for t in from_midnight[0:30]:
9798
show_tran(*t)

misc/import_ch_zurich.py

+7-6
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
"""Imports Zurich timetables, converting them from DIVA export format
1818
to Google Transit format."""
19+
from __future__ import print_function
1920

2021
# This was written before transitfeed.py and we haven't yet found the
2122
# motivation to port it. Please see the examples directory for better
@@ -225,8 +226,8 @@ def ImportStations(self, station_file, adv_file):
225226
# Line ids in this file have leading zeroes, remove.
226227
self.stations[station_id].advertised_lines.add(line_id.lstrip("0"))
227228
else:
228-
print "Warning, advertised lines file references " \
229-
"unknown station, id " + station_id
229+
print("Warning, advertised lines file references " \
230+
"unknown station, id " + station_id)
230231

231232
def ImportRoutes(self, s):
232233
"Imports the rec_lin_ber.mdv file."
@@ -360,8 +361,8 @@ def ImportTrips(self, trips_file):
360361
'FGR_NR', 'FPL_KUERZEL', 'TAGESMERKMAL_NR', 'VB',
361362
'FRT_HP_AUS', 'HALTEPUNKT_NR_ZIEL', 'FAHRTART_NR']):
362363
if trip_type != '1':
363-
print "skipping Trip ", trip_id, line, direction, \
364-
dest_station_id, trip_type
364+
print("skipping Trip ", trip_id, line, direction, \
365+
dest_station_id, trip_type)
365366
continue # 1=normal, 2=empty, 3=from depot, 4=to depot, 5=other
366367
trip = Trip()
367368
#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):
442443
trips.sort()
443444
for (trip_id, trip) in trips:
444445
if (not len(trip.pattern.stops)) or (None in trip.pattern.stops):
445-
print "*** Skipping bad trip: ", [trip.id]
446+
print("*** Skipping bad trip: ", [trip.id])
446447
continue
447448
self.goodTrips[trip_id] = True
448449
headsign = self.stations[trip.pattern.stops[-1]].name
@@ -502,7 +503,7 @@ def main(argv):
502503
importer = DivaImporter(ConvertCH1903, options.drop_unadvertised_lines)
503504
importer.Import(options.in_file)
504505
importer.Write(options.out_file)
505-
print 'Wrote output to', options.out_file
506+
print('Wrote output to', options.out_file)
506507

507508

508509
if __name__ == '__main__':

0 commit comments

Comments
 (0)