]> granicus.if.org Git - postgis/commitdiff
Modernize Python 2 code to get ready for Python 3
authorDarafei Praliaskouski <me@komzpa.net>
Sun, 9 Jun 2019 11:31:34 +0000 (11:31 +0000)
committerDarafei Praliaskouski <me@komzpa.net>
Sun, 9 Jun 2019 11:31:34 +0000 (11:31 +0000)
Patch by Christian Clauss

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

git-svn-id: http://svn.osgeo.org/postgis/trunk@17479 b70326c6-7e19-0410-871a-916f4a2858ee

NEWS
raster/scripts/python/genraster.py
raster/scripts/python/ovdump.py
raster/scripts/python/pixval.py
raster/scripts/python/raster2pgsql.py
raster/scripts/python/rtgdalraster.py
raster/scripts/python/rtpixdump.py
raster/scripts/python/rtrowdump.py
raster/scripts/python/window.py

diff --git a/NEWS b/NEWS
index 31ffb614ac2f608280ea2d1c6649f488845e0a57..5f2d12dcba1734b2a196cd4d0be5dfe26578e65a 100644 (file)
--- a/NEWS
+++ b/NEWS
@@ -155,7 +155,7 @@ PostGIS 3.0.0
   - #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
index 6d03d1ffaaf18b5c5c3f57bc0ead5c22456a0169..9806cd89255b258c75102d676ccd5d0cb5111261 100755 (executable)
@@ -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 random
 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 @@ else:
     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 @@ for j in range(0, g_size[1], g_cell_size[1]):
         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)
index f8e6d79b2cd975b77c9c43ef370ff6cdaf3aa0ac..b6c4321b55205bfd01309c9460ee4f22f68959ea 100755 (executable)
@@ -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 @@ for nv in range(nvstart, nvend):
 
     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 @@ for nv in range(nvstart, nvend):
     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 @@ for nv in range(nvstart, nvend):
         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
index ac6d4f72a0330637bc5b61c0d0ade6e2a9e46224..0477a501989333e7839be7093bce85d2cdaf0e72 100755 (executable)
@@ -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 @@ def pt2fmt(pt):
     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 @@ if len(sys.argv) > 5:
 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 @@ else:
     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 @@ pixel = src_band.ReadRaster(x - 1, y - 1, 1, 1, 1, 1)
 fmt = pt2fmt(src_band.DataType)
 pixval = struct.unpack(fmt, pixel)
 
-print "Pixel value -> %s" % str(pixval[0])
+print("Pixel value -> %s" % str(pixval[0]))
index 677eff49e1ada476b996ca325fc60b77aeb7b8bf..fb4dd1e62795b07243d3e4b74e14542e8514fc1f 100755 (executable)
@@ -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 quote_sql_name(name):
 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 check_hex(hex, bytes_size = None):
 
 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 @@ def main():
     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 @@ def main():
     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]))
 
 ################################################################################
 
index 2b32c70f65ea8973c0ba10984337d2a2a95b7734..d97d6bed6f6833eeccfc697cd5a21a8a893c69fc 100755 (executable)
@@ -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 @@ try:
        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)
index 2e0af0fac489921edad5810693574522c3b0a6e5..78e24996c327b1ab0797e0cd59a2c0c75053cc49 100755 (executable)
@@ -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 @@ try:
             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)
index 451899395125981ea98e20676afc4a6281273357..b43e38f8746046b8bfa17404a614a5fff4f1c92a 100755 (executable)
@@ -130,5 +130,5 @@ try:
         assert band is not None
         band.WriteArray(raster)
 
-except rtreader.RasterError, e:
-    print "ERROR - ", e
+except rtreader.RasterError as e:
+    print("ERROR - ", e)
index fa78e4a5c6f74d103656f502099a0fdb2b98be70..618054854baa0fda611f65f229f38389d7d5f590 100755 (executable)
 # 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
 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 @@ inxoff = int(sys.argv[2])
 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 @@ if ds is None:
 
 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 @@ ulp = ( gt[0], gt[3] ) # X/Y upper left pixel corner
 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))