From b0d3bce2dbf66bbf5b65e1fa6465cd9039fabdcd Mon Sep 17 00:00:00 2001
From: Yash Shah <yashshah0127@gmail.com>
Date: Fri, 20 Jan 2017 19:04:24 -0800
Subject: [PATCH] Add Python 3 compatibility to print statements, change xrange
 to range

---
 bin/main.py                            |  2 +-
 bin/make_cal.py                        | 14 ++++-----
 bin/monitor.py                         | 40 +++++++++++++-------------
 geomagio/Controller.py                 | 16 +++++------
 geomagio/TimeseriesFactory.py          |  6 ++--
 geomagio/TimeseriesUtility.py          |  2 +-
 geomagio/binlog/BinLogWriter.py        |  2 +-
 geomagio/edge/RawInputClient.py        |  2 +-
 geomagio/iaga2002/IAGA2002Writer.py    |  2 +-
 geomagio/imfv283/GOESIMFV283Factory.py | 15 +++++-----
 geomagio/imfv283/IMFV283Parser.py      |  6 ++--
 geomagio/pcdcp/PCDCPWriter.py          |  2 +-
 geomagio/temperature/TEMPWriter.py     |  2 +-
 geomagio/vbf/VBFWriter.py              |  2 +-
 test/ObservatoryMetadata_test.py       |  2 +-
 15 files changed, 57 insertions(+), 58 deletions(-)

diff --git a/bin/main.py b/bin/main.py
index a4ed0d8c8..5cf6dbdef 100755
--- a/bin/main.py
+++ b/bin/main.py
@@ -23,7 +23,7 @@ def main():
             interval='minute', type='variation')
     timeseries = factory.get_timeseries(
             UTCDateTime('2014-11-01'), UTCDateTime('2014-11-02'))
-    print timeseries
+    print(timeseries)
 
 
 if __name__ == '__main__':
diff --git a/bin/make_cal.py b/bin/make_cal.py
index 27acfc6e1..b644e03d4 100755
--- a/bin/make_cal.py
+++ b/bin/make_cal.py
@@ -4,7 +4,7 @@
 Usage:
     python make_cal.py OBSERVATORY YEAR
 """
-
+from __future__ import print_function
 
 from datetime import datetime
 import itertools
@@ -31,8 +31,8 @@ SERVICE_URL = 'https://geomag.usgs.gov/baselines/observation.json.php'
 # parse observatory and year arguments
 if len(sys.argv) != 3:
     cmd = sys.argv[0]
-    print >> sys.stderr, 'Usage:   {} OBSERVATORY YEAR'.format(cmd)
-    print >> sys.stderr, 'Example: {} BOU 2016'.format(cmd)
+    print('Usage:   {} OBSERVATORY YEAR'.format(cmd), file=sys.stderr)
+    print('Example: {} BOU 2016'.format(cmd), file=sys.stderr)
     sys.exit(1)
 
 OBSERVATORY = sys.argv[1]
@@ -47,14 +47,14 @@ url = SERVICE_URL + '?' + '&'.join([
 ])
 
 try:
-    print >> sys.stderr, 'Loading data from web service\n\t{}'.format(url)
+    print('Loading data from web service\n\t{}'.format(url), file=sys.stderr)
     response = urllib2.urlopen(url,
         # allow environment certificate bundle override
         cafile=os.environ.get('SSL_CERT_FILE'))
     data = response.read()
     observations = json.loads(data)
-except Exception, e:
-    print >> sys.stderr, 'Error loading data ({})'.format(str(e))
+except Exception as e:
+    print('Error loading data ({})'.format(str(e)), file=sys.stderr)
     sys.exit(1)
 
 
@@ -111,7 +111,7 @@ calfile.append('')
 
 # write calfile
 filename = FILENAME_FORMAT.format(OBSERVATORY=OBSERVATORY, YEAR=YEAR)
-print >> sys.stderr, 'Writing cal file to {}'.format(filename)
+print('Writing cal file to {}'.format(filename), file=sys.stderr)
 with open(filename, 'wb', -1) as f:
     f.write(os.linesep.join(calfile))
 
diff --git a/bin/monitor.py b/bin/monitor.py
index 2c03d8b05..012bcd68e 100755
--- a/bin/monitor.py
+++ b/bin/monitor.py
@@ -160,21 +160,21 @@ def print_html_header(starttime, endtime, title):
     title: string
         The title passed in by the user
     """
-    print '<!DOCTYPE html>\n' + \
-    '<html>\n' + \
-        '<head>\n' + \
-            '<title> %s \n to %s \n</title>' % \
-                    (format_time(starttime), format_time(endtime)) + \
-        '</head>\n' + \
-        '<body>\n' + \
-            '<style type="text/css">\n' + \
-                'table {border-collapse: collapse;}\n' + \
-                'th {border:1px solid black; padding: 2px;}\n' + \
-                'td {text-align:center;}\n' + \
-            '</style>\n' +\
-            title + '<br>\n'\
-            '%s to %s ' % \
-                (format_time(starttime), format_time(endtime))
+    print('<!DOCTYPE html>\n' +
+        '<html>\n' +
+            '<head>\n' +
+                '<title> %s \n to %s \n</title>' %
+                        (format_time(starttime), format_time(endtime)) +
+            '</head>\n' +
+            '<body>\n' +
+                '<style type="text/css">\n' +
+                    'table {border-collapse: collapse;}\n' +
+                    'th {border:1px solid black; padding: 2px;}\n' +
+                    'td {text-align:center;}\n' +
+                '</style>\n' +
+                title + '<br>\n'
+                '%s to %s ' %
+                    (format_time(starttime), format_time(endtime)))
 
 
 def print_observatories(args):
@@ -265,9 +265,9 @@ def print_observatories(args):
                     '%s %ss<br>\n' % (warning, interval)
         summary_table += table_end
         if print_it:
-            print summary_header
-            print summary_table
-            print gap_details
+            print(summary_header)
+            print(summary_table)
+            print(gap_details)
 
     return warning_issued
 
@@ -287,8 +287,8 @@ def main(args):
     print_html_header(args.starttime, args.endtime, args.title)
 
     warning_issued = print_observatories(args)
-    print '</body>\n' + \
-          '</html>\n'
+    print('</body>\n' +
+          '</html>\n')
 
     sys.exit(warning_issued)
 
diff --git a/geomagio/Controller.py b/geomagio/Controller.py
index 27a2e90d1..ece81ed6a 100644
--- a/geomagio/Controller.py
+++ b/geomagio/Controller.py
@@ -1,5 +1,5 @@
 """Controller class for geomag algorithms"""
-from __future__ import absolute_import
+from __future__ import absolute_import, print_function
 
 import argparse
 import sys
@@ -207,8 +207,8 @@ class Controller(object):
         if options.update_limit != 0:
             if update_count >= options.update_limit:
                 return
-        print >> sys.stderr, 'checking gaps', \
-                options.starttime, options.endtime
+        print('checking gaps', options.starttime, options.endtime,
+            file=sys.stderr)
         algorithm = self._algorithm
         input_channels = options.inchannels or \
                 algorithm.get_input_channels()
@@ -254,8 +254,8 @@ class Controller(object):
             # fill gap
             options.starttime = output_gap[0]
             options.endtime = output_gap[1]
-            print >> sys.stderr, 'processing', \
-                    options.starttime, options.endtime
+            print('processing', options.starttime, options.endtime,
+                file=sys.stderr)
             self.run(options, input_timeseries)
 
 
@@ -470,12 +470,12 @@ def main(args):
         usingDeprecated = True
 
     if usingDeprecated:
-        print >> sys.stderr, 'WARNING: you are using deprecated arguments,' + \
-                ' please update your usage'
+        print('WARNING: you are using deprecated arguments,' +
+              ' please update your usage', file=sys.stderr)
     # TODO check for unused arguments.
 
     # make sure observatory is a tuple
-    if isinstance(args.observatory, (str, unicode)):
+    if isinstance(args.observatory, (str, str)):
         args.observatory = (args.observatory,)
 
     if args.observatory_foreach:
diff --git a/geomagio/TimeseriesFactory.py b/geomagio/TimeseriesFactory.py
index 1f29ed1da..8867490e1 100644
--- a/geomagio/TimeseriesFactory.py
+++ b/geomagio/TimeseriesFactory.py
@@ -1,5 +1,5 @@
 """Abstract Timeseries Factory Interface."""
-from __future__ import absolute_import
+from __future__ import absolute_import, print_function
 
 import numpy
 import obspy.core
@@ -120,8 +120,8 @@ class TimeseriesFactory(object):
             except NotImplementedError:
                 raise NotImplementedError('"get_timeseries" not implemented')
             except Exception as e:
-                print >> sys.stderr, "Error parsing data: " + str(e)
-                print >> sys.stderr, data
+                print("Error parsing data: " + str(e), file=sys.stderr)
+                print(data, file=sys.stderr)
         if channels is not None:
             filtered = obspy.core.Stream()
             for channel in channels:
diff --git a/geomagio/TimeseriesUtility.py b/geomagio/TimeseriesUtility.py
index 1e9061c0b..c9b9d737f 100644
--- a/geomagio/TimeseriesUtility.py
+++ b/geomagio/TimeseriesUtility.py
@@ -47,7 +47,7 @@ def get_trace_gaps(trace):
     starttime = stats.starttime
     length = len(data)
     delta = stats.delta
-    for i in xrange(0, length):
+    for i in range(0, length):
         if numpy.isnan(data[i]):
             if gap is None:
                 # start of a gap
diff --git a/geomagio/binlog/BinLogWriter.py b/geomagio/binlog/BinLogWriter.py
index abea776cd..23927fc40 100644
--- a/geomagio/binlog/BinLogWriter.py
+++ b/geomagio/binlog/BinLogWriter.py
@@ -118,7 +118,7 @@ class BinLogWriter(object):
         starttime = float(traces[0].stats.starttime)
         delta = traces[0].stats.delta
 
-        for i in xrange(len(traces[0].data)):
+        for i in range(len(traces[0].data)):
             self._format_values(
                 datetime.utcfromtimestamp(starttime + i * delta),
                 (t.data[i] for t in traces))
diff --git a/geomagio/edge/RawInputClient.py b/geomagio/edge/RawInputClient.py
index 799099b20..916b24951 100644
--- a/geomagio/edge/RawInputClient.py
+++ b/geomagio/edge/RawInputClient.py
@@ -184,7 +184,7 @@ class RawInputClient():
             raise TimeseriesFactoryException(
                     'Unsupported interval for RawInputClient')
 
-        for i in xrange(0, totalsamps, nsamp):
+        for i in range(0, totalsamps, nsamp):
             if totalsamps - i < nsamp:
                 endsample = totalsamps
             else:
diff --git a/geomagio/iaga2002/IAGA2002Writer.py b/geomagio/iaga2002/IAGA2002Writer.py
index 5a1e2ce3a..2f03bdf22 100644
--- a/geomagio/iaga2002/IAGA2002Writer.py
+++ b/geomagio/iaga2002/IAGA2002Writer.py
@@ -216,7 +216,7 @@ class IAGA2002Writer(object):
         traces = [timeseries.select(channel=c)[0] for c in channels]
         starttime = float(traces[0].stats.starttime)
         delta = traces[0].stats.delta
-        for i in xrange(len(traces[0].data)):
+        for i in range(len(traces[0].data)):
             buf.append(self._format_values(
                 datetime.utcfromtimestamp(starttime + i * delta),
                 (t.data[i] for t in traces)))
diff --git a/geomagio/imfv283/GOESIMFV283Factory.py b/geomagio/imfv283/GOESIMFV283Factory.py
index fc75ac42d..a3bf818a1 100644
--- a/geomagio/imfv283/GOESIMFV283Factory.py
+++ b/geomagio/imfv283/GOESIMFV283Factory.py
@@ -1,5 +1,5 @@
 """Factory to load IMFV283 files from an input StreamIMFV283Factory."""
-from __future__ import absolute_import
+from __future__ import absolute_import, print_function
 
 from .IMFV283Factory import IMFV283Factory
 import subprocess
@@ -69,8 +69,8 @@ class GOESIMFV283Factory(IMFV283Factory):
         timeseries.trim(starttime, endtime)
         # output the number of points we read for logging
         if len(timeseries):
-            print >> sys.stderr, "Read %s points from %s" % \
-                (timeseries[0].stats.npts, observatory)
+            print("Read %s points from %s" % (timeseries[0].stats.npts,
+                observatory), file=sys.stderr)
 
         self._post_process(timeseries)
         if observatory is not None:
@@ -125,7 +125,7 @@ class GOESIMFV283Factory(IMFV283Factory):
         self._fill_criteria_file(starttime, endtime, observatory)
 
         for server in self.server:
-            print >> sys.stderr, server
+            print(server, file=sys.stderr)
             proc = subprocess.Popen(
                     [self.getdcpmessages,
                     '-h', server,
@@ -135,11 +135,10 @@ class GOESIMFV283Factory(IMFV283Factory):
                     '-t', '60',
                     '-n'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
             (output, error) = proc.communicate()
-            print >> sys.stderr, error
+            print(error, file=sys.stderr)
             if error.find(self.javaerror) >= 0:
-                print >> sys.stderr, \
-                        'Error: could not connect to %s' % \
-                        server
+                print('Error: could not connect to %s' % server,
+                    file=sys.stderr)
                 continue
             break
 
diff --git a/geomagio/imfv283/IMFV283Parser.py b/geomagio/imfv283/IMFV283Parser.py
index 32e83acba..1a852f510 100644
--- a/geomagio/imfv283/IMFV283Parser.py
+++ b/geomagio/imfv283/IMFV283Parser.py
@@ -118,7 +118,7 @@ class IMFV283Parser(object):
             parse_data[channel] = []
 
         bytecount = 30
-        for cnt in xrange(0, 12):
+        for cnt in range(0, 12):
             # get data in 2 byte pairs as integers.
             d1 = 0x100 * data[bytecount] + data[bytecount + 1]
             d2 = 0x100 * data[bytecount + 2] + data[bytecount + 3]
@@ -285,7 +285,7 @@ class IMFV283Parser(object):
         scale = goes_header['scale']
         offset = goes_header['offset']
         orientation = goes_header['orient']
-        for channel, loc in zip(CHANNELS[orientation], xrange(0, 4)):
+        for channel, loc in zip(CHANNELS[orientation], range(0, 4)):
             stats = obspy.core.Stats()
             stats.channel = channel
             stats.sampling_rate = 0.0166666666667
@@ -327,7 +327,7 @@ class IMFV283Parser(object):
         else:
             offset = HEADER_SIZE
 
-        for cnt in xrange(0, 63):
+        for cnt in range(0, 63):
             # Convert 3 byte "pair" into ordinal values for manipulation.
             byte3 = ord(msg[offset + ness_byte + 2])
             byte2 = ord(msg[offset + ness_byte + 1])
diff --git a/geomagio/pcdcp/PCDCPWriter.py b/geomagio/pcdcp/PCDCPWriter.py
index 02c78ccb3..1fbff2d0d 100644
--- a/geomagio/pcdcp/PCDCPWriter.py
+++ b/geomagio/pcdcp/PCDCPWriter.py
@@ -110,7 +110,7 @@ class PCDCPWriter(object):
         starttime = float(traces[0].stats.starttime)
         delta = traces[0].stats.delta
 
-        for i in xrange(len(traces[0].data)):
+        for i in range(len(traces[0].data)):
             buf.append(self._format_values(
                 datetime.utcfromtimestamp(starttime + i * delta),
                 (t.data[i] for t in traces), stats))
diff --git a/geomagio/temperature/TEMPWriter.py b/geomagio/temperature/TEMPWriter.py
index f29cbedd9..d2d8c21ea 100644
--- a/geomagio/temperature/TEMPWriter.py
+++ b/geomagio/temperature/TEMPWriter.py
@@ -94,7 +94,7 @@ class TEMPWriter(object):
         starttime = float(traces[0].stats.starttime)
         delta = traces[0].stats.delta
 
-        for i in xrange(len(traces[0].data)):
+        for i in range(len(traces[0].data)):
             buf.append(self._format_values(
                 datetime.utcfromtimestamp(starttime + i * delta),
                 (t.data[i] for t in traces)))
diff --git a/geomagio/vbf/VBFWriter.py b/geomagio/vbf/VBFWriter.py
index b7751b9a3..9115ed0ff 100644
--- a/geomagio/vbf/VBFWriter.py
+++ b/geomagio/vbf/VBFWriter.py
@@ -99,7 +99,7 @@ class VBFWriter(object):
         starttime = float(traces[0].stats.starttime)
         delta = traces[0].stats.delta
 
-        for i in xrange(len(traces[0].data)):
+        for i in range(len(traces[0].data)):
             buf.append(self._format_values(
                 datetime.utcfromtimestamp(starttime + i * delta),
                 (t.data[i] for t in traces)))
diff --git a/test/ObservatoryMetadata_test.py b/test/ObservatoryMetadata_test.py
index 09f12d586..f5e37d654 100644
--- a/test/ObservatoryMetadata_test.py
+++ b/test/ObservatoryMetadata_test.py
@@ -67,5 +67,5 @@ def test_set_metadata():
     observatorymetadata.set_metadata(stats, 'BOU', 'MVH',
             'quasi-definitive', 'second')
     assert_equals(stats['declination_base'], 20000)
-    print stats
+    print(stats)
     assert_equals(stats['data_interval_type'], 'Average 1-Second')
-- 
GitLab