[postgis-tickets] r17479 - Modernize Python 2 code to get ready for Python 3

Darafei komzpa at gmail.com
Sun Jun 9 04:31:35 PDT 2019


Author: komzpa
Date: 2019-06-09 04:31:34 -0700 (Sun, 09 Jun 2019)
New Revision: 17479

Modified:
   trunk/NEWS
   trunk/raster/scripts/python/genraster.py
   trunk/raster/scripts/python/ovdump.py
   trunk/raster/scripts/python/pixval.py
   trunk/raster/scripts/python/raster2pgsql.py
   trunk/raster/scripts/python/rtgdalraster.py
   trunk/raster/scripts/python/rtpixdump.py
   trunk/raster/scripts/python/rtrowdump.py
   trunk/raster/scripts/python/window.py
Log:
Modernize Python 2 code to get ready for Python 3

Patch by Christian Clauss

Closes #4422
Closes https://github.com/postgis/postgis/pull/410


Modified: trunk/NEWS
===================================================================
--- trunk/NEWS	2019-06-06 10:24:48 UTC (rev 17478)
+++ trunk/NEWS	2019-06-09 11:31:34 UTC (rev 17479)
@@ -155,9 +155,9 @@
   - #4412, Support ingesting rasters with NODATA=NaN (Darafei Praliaskouski)
   - #4413, Raster tile size follows GeoTIFF block size on raster2pgsql -t auto
            (Darafei Praliaskouski)
+  - #4422, Modernize Python 2 code to get ready for Python 3 (Christian Clauss)
 
 
-
 PostGIS 2.5.0
 2018/09/23
 WARNING: If compiling with PostgreSQL+JIT, LLVM >= 6 is required

Modified: trunk/raster/scripts/python/genraster.py
===================================================================
--- trunk/raster/scripts/python/genraster.py	2019-06-06 10:24:48 UTC (rev 17478)
+++ trunk/raster/scripts/python/genraster.py	2019-06-09 11:31:34 UTC (rev 17479)
@@ -26,6 +26,7 @@
 # Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 #
 ###############################################################################
+from __future__ import print_function
 import Image
 import ImageDraw
 import ImageFont
@@ -33,8 +34,8 @@
 import sys
 
 if len(sys.argv) < 5 or len(sys.argv) > 6:
-    print 'Usage: genraster.py <xsize> <ysize> <xsizecell> <ysizecell> <outline colour>'
-    print 'Note: Generated image is saved as out.png'
+    print('Usage: genraster.py <xsize> <ysize> <xsizecell> <ysizecell> <outline colour>')
+    print('Note: Generated image is saved as out.png')
     sys.exit(1)
 
 g_file = "out.png"
@@ -46,8 +47,8 @@
     g_outline = None
 
 ncells = (g_size[0] / g_cell_size[0]) * (g_size[1] / g_cell_size[1])
-print 'Number of cells: ',ncells
-print 'ID \tULX\tULY\tCLR\tTXTCLR\tOUTCLR'
+print('Number of cells: ',ncells)
+print('ID \tULX\tULY\tCLR\tTXTCLR\tOUTCLR')
 
 img = Image.new("L", g_size, 255)
 draw = ImageDraw.Draw(img)
@@ -74,9 +75,9 @@
         draw.rectangle( [(i,j), (i + g_cell_size[0], j + g_cell_size[1])], fill=value, outline=g_outline)
         draw.text( (i,j), ('%d' % count), fill=value_text, font=font)
 
-        print '%d:\t%d\t%d\t%d\t%d\t%s' % (count, i, j, value, value_text, str(g_outline))
+        print('%d:\t%d\t%d\t%d\t%d\t%s' % (count, i, j, value, value_text, str(g_outline)))
         count = count + 1
 
 del draw
 img.save(g_file, 'PNG')
-print 'Output saved: %s' % g_file
+print('Output saved: %s' % g_file)

Modified: trunk/raster/scripts/python/ovdump.py
===================================================================
--- trunk/raster/scripts/python/ovdump.py	2019-06-06 10:24:48 UTC (rev 17478)
+++ trunk/raster/scripts/python/ovdump.py	2019-06-09 11:31:34 UTC (rev 17479)
@@ -24,6 +24,7 @@
 # Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 #
 
+from __future__ import print_function
 from osgeo import gdal
 from osgeo import osr
 import osgeo.gdalconst as gdalc
@@ -66,13 +67,13 @@
 
     band = src_ds.GetRasterBand(1)
     if nv < 0 and nv >= band.GetOverviewCount():
-        print "ERROR: Failed to find overview %d" % nv
+        print("ERROR: Failed to find overview %d" % nv)
         sys.exit(1)
     ov_band = band.GetOverview(nv)
 
     ovf = int(0.5 + band.XSize / float(ov_band.XSize))
 
-    print "--- OVERVIEW #%d level = %d ---------------------------------------" % (nv + 1, ovf)
+    print("--- OVERVIEW #%d level = %d ---------------------------------------" % (nv + 1, ovf))
 
     # Destination
     dst_file = os.path.basename(opts.raster) + "_ov_" + str(ovf) + ".tif"
@@ -80,9 +81,9 @@
     dst_drv = gdal.GetDriverByName(dst_format)
     dst_ds = dst_drv.Create(dst_file, ov_band.XSize, ov_band.YSize, src_ds.RasterCount, ov_band.DataType)
 
-    print "Source: " + opts.raster
-    print "Target: " + dst_file
-    print "Exporting %d bands of size %d x %d" % (src_ds.RasterCount, ov_band.XSize, ov_band.YSize)
+    print("Source: " + opts.raster)
+    print("Target: " + dst_file)
+    print("Exporting %d bands of size %d x %d" % (src_ds.RasterCount, ov_band.XSize, ov_band.YSize))
 
     # Rewrite bands of overview to output file
     ov_band = None
@@ -95,8 +96,8 @@
         ov_band = band.GetOverview(nv)
         assert ov_band is not None
 
-        print " Band #%d (%s) (%d x %d)" % \
-              (nb, gdal.GetDataTypeName(ov_band.DataType), ov_band.XSize, ov_band.YSize)
+        print(" Band #%d (%s) (%d x %d)" % \
+              (nb, gdal.GetDataTypeName(ov_band.DataType), ov_band.XSize, ov_band.YSize))
 
         dst_band = dst_ds.GetRasterBand(nb)
         assert dst_band is not None

Modified: trunk/raster/scripts/python/pixval.py
===================================================================
--- trunk/raster/scripts/python/pixval.py	2019-06-06 10:24:48 UTC (rev 17478)
+++ trunk/raster/scripts/python/pixval.py	2019-06-09 11:31:34 UTC (rev 17479)
@@ -21,6 +21,7 @@
 # Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 #
 
+from __future__ import print_function
 from osgeo import gdal
 from osgeo import osr
 import osgeo.gdalconst as gdalc
@@ -40,12 +41,12 @@
     return fmttypes.get(pt, 'x')
 
 if len(sys.argv) < 5 or len(sys.argv) > 6:
-    print "Usage: pixval.py <raster> <band> <x> <y>"
-    print "\traster - GDAL supported dataset"
-    print "\tband - 1-based number of band"
-    print "\toverview - optional 1-based number of overview"
-    print "\tx - Pixel column - 1..N where N is raster X dimension"
-    print "\ty - Pixel row - 1..N where N is raster Y dimension"
+    print("Usage: pixval.py <raster> <band> <x> <y>")
+    print("\traster - GDAL supported dataset")
+    print("\tband - 1-based number of band")
+    print("\toverview - optional 1-based number of overview")
+    print("\tx - Pixel column - 1..N where N is raster X dimension")
+    print("\ty - Pixel row - 1..N where N is raster Y dimension")
     sys.exit(0)
 
 infile = sys.argv[1]
@@ -57,11 +58,11 @@
 else:
     noverview = None
 
-print "File : %s" % infile
-print "Band : %d" % nband
+print("File : %s" % infile)
+print("Band : %d" % nband)
 if noverview is not None:
-    print "Overview: %d" % noverview
-print "Pixel: %d x %d" % (x, y)
+    print("Overview: %d" % noverview)
+print("Pixel: %d x %d" % (x, y))
 
 ds = gdal.Open(infile, gdalc.GA_ReadOnly);
 if ds is None:
@@ -77,13 +78,13 @@
     if noverview > 0 and noverview <= band.GetOverviewCount():
         src_band = band.GetOverview(noverview - 1)
     else:
-        print "ERROR: Invalid overview index"
-        print "Band %d consists of %d overivews" % (nband, band.GetOverviewCount())
+        print("ERROR: Invalid overview index")
+        print("Band %d consists of %d overivews" % (nband, band.GetOverviewCount()))
         sys.exit(1)
 
 if x <= 0 or x > src_band.XSize or y <= 0 or y > src_band.YSize:
-    print "ERROR: Invalid pixel coordinates"
-    print "Band or overview dimensions are %d x %d" % (src_band.XSize, src_band.YSize)
+    print("ERROR: Invalid pixel coordinates")
+    print("Band or overview dimensions are %d x %d" % (src_band.XSize, src_band.YSize))
     sys.exit(1)
 
 # Pixel index is 0-based
@@ -92,4 +93,4 @@
 fmt = pt2fmt(src_band.DataType)
 pixval = struct.unpack(fmt, pixel)
 
-print "Pixel value -> %s" % str(pixval[0])
+print("Pixel value -> %s" % str(pixval[0]))

Modified: trunk/raster/scripts/python/raster2pgsql.py
===================================================================
--- trunk/raster/scripts/python/raster2pgsql.py	2019-06-06 10:24:48 UTC (rev 17478)
+++ trunk/raster/scripts/python/raster2pgsql.py	2019-06-09 11:31:34 UTC (rev 17479)
@@ -30,6 +30,7 @@
 # Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 ################################################################################
 #
+from __future__ import print_function
 from osgeo import gdal
 from osgeo import osr
 import osgeo.gdalconst as gdalc
@@ -303,7 +304,7 @@
 def make_sql_value_array(values):
     sql = "ARRAY["
     for v in values:
-        if type(v) == str:
+        if isinstance(v, str):
             sql += quote_sql_value(v) + ","
         else:
             sql += str(v) + ','
@@ -628,15 +629,15 @@
 
 def dump_block_numpy(pixels):
     assert pixels.ndim == 2
-    print 'BEGIN BLOCK SCANLINES (numpy): (%d, %d)' %(len(pixels[0]), len(pixels))
+    print('BEGIN BLOCK SCANLINES (numpy): (%d, %d)' %(len(pixels[0]), len(pixels)))
 
     i = 0
     for row in range (0, len(pixels)):
         s = binascii.hexlify(pixels[row])
-        print '%d (%d)\t%s' % (i, (len(s) / 2), s)
+        print('%d (%d)\t%s' % (i, (len(s) / 2), s))
         i = i + 1
 
-    print 'END BLOCK SCANLINES'
+    print('END BLOCK SCANLINES')
 
 def fetch_band_nodata(band, default = 0):
     assert band is not None
@@ -962,7 +963,7 @@
     SUMMARY = []
     
     saved_out = sys.stdout
-    if type(opts.output) is str:
+    if isinstance(opts.output, str):
         filename = opts.output
         opts.output = open(filename, "w")
 
@@ -1019,19 +1020,19 @@
     if opts.output != sys.stdout:
         sys.stdout = saved_out
 
-        print "------------------------------------------------------------"
-        print " Summary of GDAL to PostGIS Raster processing:"
-        print "------------------------------------------------------------"
+        print("------------------------------------------------------------")
+        print(" Summary of GDAL to PostGIS Raster processing:")
+        print("------------------------------------------------------------")
         if i == 1:
             m = '%d (%s)' % (i, infile)
         else:
             m = '%d' % i
-        print "Number of processed raster files: " + m
-        print "List of generated tables (number of tiles):"
+        print("Number of processed raster files: " + m)
+        print("List of generated tables (number of tiles):")
         i = 0
         for s in SUMMARY:
             i += 1
-            print "%d\t%s (%d)" % (i, s[0], s[1])
+            print("%d\t%s (%d)" % (i, s[0], s[1]))
 
 ################################################################################
 

Modified: trunk/raster/scripts/python/rtgdalraster.py
===================================================================
--- trunk/raster/scripts/python/rtgdalraster.py	2019-06-06 10:24:48 UTC (rev 17478)
+++ trunk/raster/scripts/python/rtgdalraster.py	2019-06-09 11:31:34 UTC (rev 17479)
@@ -28,6 +28,7 @@
 # along with this program; if not, write to the Free Software Foundation,
 # Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 ###############################################################################
+from __future__ import print_function
 from optparse import OptionParser
 import sys
 import os
@@ -92,7 +93,7 @@
 	cur.close();
 	conn.close();
 
-	print "raster outputted to %s" % opts.output;
+	print("raster outputted to %s" % opts.output);
 
-except Exception, e:
-    print "ERROR: ", e
+except Exception as e:
+    print("ERROR: ", e)

Modified: trunk/raster/scripts/python/rtpixdump.py
===================================================================
--- trunk/raster/scripts/python/rtpixdump.py	2019-06-06 10:24:48 UTC (rev 17478)
+++ trunk/raster/scripts/python/rtpixdump.py	2019-06-09 11:31:34 UTC (rev 17479)
@@ -21,6 +21,7 @@
 # Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 #
 ###############################################################################
+from __future__ import print_function
 import rtreader
 from optparse import OptionParser
 import sys
@@ -69,8 +70,8 @@
             scanline = ""
             for x in range(1, rast.width + 1):
                 scanline += str(int(rast.get_value(band, x, y))) + '\t'
-            print scanline
-        print # Bands separator
+            print(scanline)
+        print() # Bands separator
 
-except rtreader.RasterError, e:
-    print "ERROR - ", e
+except rtreader.RasterError as e:
+    print("ERROR - ", e)

Modified: trunk/raster/scripts/python/rtrowdump.py
===================================================================
--- trunk/raster/scripts/python/rtrowdump.py	2019-06-06 10:24:48 UTC (rev 17478)
+++ trunk/raster/scripts/python/rtrowdump.py	2019-06-09 11:31:34 UTC (rev 17479)
@@ -130,5 +130,5 @@
         assert band is not None
         band.WriteArray(raster)
 
-except rtreader.RasterError, e:
-    print "ERROR - ", e
+except rtreader.RasterError as e:
+    print("ERROR - ", e)

Modified: trunk/raster/scripts/python/window.py
===================================================================
--- trunk/raster/scripts/python/window.py	2019-06-06 10:24:48 UTC (rev 17478)
+++ trunk/raster/scripts/python/window.py	2019-06-09 11:31:34 UTC (rev 17479)
@@ -21,6 +21,7 @@
 # along with this program; if not, write to the Free Software Foundation,
 # Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 ##############################################################################
+from __future__ import print_function
 from osgeo import gdal
 from osgeo import osr
 import osgeo.gdalconst as gdalc
@@ -27,12 +28,12 @@
 import sys
 
 if len(sys.argv) != 6:
-    print "Usage: window.py <raster> <x> <y> <xsize> <ysize>"
-    print "\traster - GDAL supported dataset"
-    print "\tx - column - 1..N where N is raster X dimension"
-    print "\ty - row - 1..N where N is raster Y dimension"
-    print "\txsize - x-dimension of requested window (xsize <= xsize of raster - x)"
-    print "\tysize - y-dimension of requested window (ysize <= ysize of raster - y)"
+    print("Usage: window.py <raster> <x> <y> <xsize> <ysize>")
+    print("\traster - GDAL supported dataset")
+    print("\tx - column - 1..N where N is raster X dimension")
+    print("\ty - row - 1..N where N is raster Y dimension")
+    print("\txsize - x-dimension of requested window (xsize <= xsize of raster - x)")
+    print("\tysize - y-dimension of requested window (ysize <= ysize of raster - y)")
     sys.exit(0)
 
 def is_georeferenced(gt):
@@ -55,11 +56,11 @@
 inyoff = int(sys.argv[3])
 inxsize = int(sys.argv[4])
 inysize = int(sys.argv[5])
-print "=== INPUT ==="
-print "File: %s" % infile
-print "Window:"
-print "- upper-left: %d x %d" % (inxoff, inyoff)
-print "- dimensions: %d x %d" % (inxsize, inysize)
+print("=== INPUT ===")
+print("File: %s" % infile)
+print("Window:")
+print("- upper-left: %d x %d" % (inxoff, inyoff))
+print("- dimensions: %d x %d" % (inxsize, inysize))
 
 ds = gdal.Open(infile, gdalc.GA_ReadOnly);
 if ds is None:
@@ -67,11 +68,11 @@
 
 xsize = ds.RasterXSize
 ysize = ds.RasterYSize
-print "=== RASTER ==="
-print "- dimensions: %d x %d" % (xsize, ysize)
+print("=== RASTER ===")
+print("- dimensions: %d x %d" % (xsize, ysize))
 
 if inxsize > xsize or inysize > ysize or inxoff > xsize or inyoff > ysize:
-    print "Invalid size of input window"
+    print("Invalid size of input window")
     sys.exit(1)
 
 gt = ds.GetGeoTransform()
@@ -80,16 +81,16 @@
 rot = ( gt[2], gt[4] ) # X-/Y-axis rotation
 
 if is_georeferenced(gt):
-    print "- pixel size:", res
-    print "- upper left:", ulp
-    print "- rotation  :", rot
+    print("- pixel size:", res)
+    print("- upper left:", ulp)
+    print("- rotation  :", rot)
 else:
-    print "No georeferencing is available"
+    print("No georeferencing is available")
     sys.exit(1)
 
-print "=== WINDOW ==="
-print "- upper-left :", calculate_corner(gt, inxoff, inyoff)
-print "- lower-left :", calculate_corner(gt, inxoff, ysize)
-print "- upper-right:", calculate_corner(gt, xsize, inyoff)
-print "- lower-right:", calculate_corner(gt, xsize, ysize)
-print "- center     :", calculate_corner(gt, xsize/2, ysize/2)
+print("=== WINDOW ===")
+print("- upper-left :", calculate_corner(gt, inxoff, inyoff))
+print("- lower-left :", calculate_corner(gt, inxoff, ysize))
+print("- upper-right:", calculate_corner(gt, xsize, inyoff))
+print("- lower-right:", calculate_corner(gt, xsize, ysize))
+print("- center     :", calculate_corner(gt, xsize/2, ysize/2))



More information about the postgis-tickets mailing list