소스 검색

grass71/scripts: apply pep8 and make them readable for python3

git-svn-id: https://svn.osgeo.org/grass/grass/trunk@68140 15284696-431f-4ddb-bdfa-cd5b030d7da7
Pietro Zambelli 9 년 전
부모
커밋
e2927d6a01
76개의 변경된 파일3308개의 추가작업 그리고 2867개의 파일을 삭제
  1. 60 51
      scripts/d.correlate/d.correlate.py
  2. 44 20
      scripts/d.frame/d.frame.py
  3. 167 136
      scripts/d.polar/d.polar.py
  4. 474 446
      scripts/d.rast.edit/d.rast.edit.py
  5. 4 2
      scripts/d.rast.leg/d.rast.leg.py
  6. 10 9
      scripts/d.redraw/d.redraw.py
  7. 44 43
      scripts/db.dropcolumn/db.dropcolumn.py
  8. 31 29
      scripts/db.in.ogr/db.in.ogr.py
  9. 28 30
      scripts/db.out.ogr/db.out.ogr.py
  10. 31 30
      scripts/db.test/db.test.py
  11. 93 60
      scripts/db.univar/db.univar.py
  12. 34 29
      scripts/g.extension.all/g.extension.all.py
  13. 17 14
      scripts/g.extension/g.extension.py
  14. 1 1
      scripts/g.extension/testsuite/test_addons_modules.py
  15. 24 20
      scripts/g.manual/g.manual.py
  16. 25 17
      scripts/g.search.modules/g.search.modules.py
  17. 1 1
      scripts/g.search.modules/testsuite/test_g_search_modules.py
  18. 88 91
      scripts/i.colors.enhance/i.colors.enhance.py
  19. 33 30
      scripts/i.image.mosaic/i.image.mosaic.py
  20. 114 106
      scripts/i.in.spotvgt/i.in.spotvgt.py
  21. 1 2
      scripts/i.oif/i.oif.py
  22. 25 23
      scripts/i.spectral/i.spectral.py
  23. 20 20
      scripts/i.tasscap/i.tasscap.py
  24. 8 7
      scripts/m.proj/m.proj.py
  25. 50 44
      scripts/r.blend/r.blend.py
  26. 18 15
      scripts/r.buffer.lowmem/r.buffer.lowmem.py
  27. 88 86
      scripts/r.colors.stddev/r.colors.stddev.py
  28. 108 81
      scripts/r.fillnulls/r.fillnulls.py
  29. 7 6
      scripts/r.grow/r.grow.py
  30. 15 6
      scripts/r.import/r.import.py
  31. 39 38
      scripts/r.in.aster/r.in.aster.py
  32. 43 42
      scripts/r.in.srtm/r.in.srtm.py
  33. 14 12
      scripts/r.in.wms/r.in.wms.py
  34. 8 7
      scripts/r.in.wms/srs.py
  35. 162 138
      scripts/r.in.wms/wms_base.py
  36. 88 76
      scripts/r.in.wms/wms_cap_parsers.py
  37. 305 217
      scripts/r.in.wms/wms_drv.py
  38. 57 53
      scripts/r.in.wms/wms_gdal_drv.py
  39. 29 21
      scripts/r.mask/r.mask.py
  40. 1 0
      scripts/r.out.xyz/r.out.xyz.py
  41. 19 17
      scripts/r.pack/r.pack.py
  42. 29 29
      scripts/r.plane/r.plane.py
  43. 1 1
      scripts/r.reclass.area/r.reclass.area.py
  44. 5 3
      scripts/r.shade/r.shade.py
  45. 48 38
      scripts/r.tileset/r.tileset.py
  46. 13 11
      scripts/r.unpack/r.unpack.py
  47. 2 2
      scripts/r3.in.xyz/r3.in.xyz.py
  48. 5 4
      scripts/v.build.all/v.build.all.py
  49. 7 8
      scripts/v.centroids/v.centroids.py
  50. 17 15
      scripts/v.db.addcolumn/v.db.addcolumn.py
  51. 31 29
      scripts/v.db.addtable/v.db.addtable.py
  52. 22 22
      scripts/v.db.dropcolumn/v.db.dropcolumn.py
  53. 1 1
      scripts/v.db.droprow/v.db.droprow.py
  54. 34 32
      scripts/v.db.droptable/v.db.droptable.py
  55. 5 3
      scripts/v.db.join/v.db.join.py
  56. 115 90
      scripts/v.db.reconnect.all/v.db.reconnect.all.py
  57. 16 11
      scripts/v.db.renamecolumn/v.db.renamecolumn.py
  58. 19 20
      scripts/v.db.univar/v.db.univar.py
  59. 6 4
      scripts/v.db.update/v.db.update.py
  60. 20 16
      scripts/v.dissolve/v.dissolve.py
  61. 11 7
      scripts/v.import/v.import.py
  62. 65 63
      scripts/v.in.e00/v.in.e00.py
  63. 46 46
      scripts/v.in.geonames/v.in.geonames.py
  64. 6 9
      scripts/v.in.lines/v.in.lines.py
  65. 28 28
      scripts/v.in.mapgen/v.in.mapgen.py
  66. 7 7
      scripts/v.in.wfs/v.in.wfs.py
  67. 154 138
      scripts/v.krige/v.krige.py
  68. 27 25
      scripts/v.pack/v.pack.py
  69. 9 9
      scripts/v.rast.stats/testsuite/test_v_rast_stats.py
  70. 9 5
      scripts/v.rast.stats/v.rast.stats.py
  71. 25 23
      scripts/v.report/v.report.py
  72. 7 6
      scripts/v.unpack/v.unpack.py
  73. 6 6
      scripts/v.what.strds/testsuite/test_what_strds.py
  74. 4 3
      scripts/v.what.strds/v.what.strds.py
  75. 2 2
      scripts/wxpyimgview/wxpyimgview.py
  76. 78 75
      scripts/wxpyimgview/wxpyimgview_gui.py

+ 60 - 51
scripts/d.correlate/d.correlate.py

@@ -29,21 +29,23 @@
 import sys
 import sys
 import os
 import os
 from grass.script.utils import try_remove
 from grass.script.utils import try_remove
-from grass.script import core as grass
+from grass.script import core as gcore
+
 
 
 def main():
 def main():
     layers = options['map'].split(',')
     layers = options['map'].split(',')
 
 
     if len(layers) < 2:
     if len(layers) < 2:
-	grass.error(_("At least 2 maps are required"))
+        gcore.error(_("At least 2 maps are required"))
 
 
-    tmpfile = grass.tempfile()
+    tmpfile = gcore.tempfile()
 
 
     for map in layers:
     for map in layers:
-	if not grass.find_file(map, element = 'cell')['file']:
-	    grass.fatal(_("Raster map <%s> not found") % map)
+        if not gcore.find_file(map, element='cell')['file']:
+            gcore.fatal(_("Raster map <%s> not found") % map)
 
 
-    grass.write_command('d.text', color = 'black', size = 4, line = 1, stdin = "CORRELATION")
+    gcore.write_command('d.text', color='black', size=4, line=1,
+                        stdin="CORRELATION")
 
 
     os.environ['GRASS_RENDER_FILE_READ'] = 'TRUE'
     os.environ['GRASS_RENDER_FILE_READ'] = 'TRUE'
 
 
@@ -52,53 +54,60 @@ def main():
     iloop = 0
     iloop = 0
     jloop = 0
     jloop = 0
     for iloop, i in enumerate(layers):
     for iloop, i in enumerate(layers):
-	for jloop, j in enumerate(layers):
-	    if i != j and iloop <= jloop:
-		color = colors[0]
-		colors = colors[1:]
-		colors.append(color)
-		grass.write_command('d.text', color = color, size = 4, line = line, stdin = "%s %s" % (i, j))
-		line += 1
-
-		ofile = file(tmpfile, 'w')
-		grass.run_command('r.stats', flags = 'cnA', input = (i, j), stdout = ofile)
-		ofile.close()
-
-		ifile = file(tmpfile, 'r')
-		first = True
-		for l in ifile:
-		    f = l.rstrip('\r\n').split(' ')
-		    x = float(f[0])
-		    y = float(f[1])
-		    if first:
-			minx = maxx = x
-			miny = maxy = y
-			first = False
-		    if minx > x: minx = x
-		    if maxx < x: maxx = x
-		    if miny > y: miny = y
-		    if maxy < y: maxy = y
-		ifile.close()
-
-		kx = 100.0/(maxx-minx+1)
-		ky = 100.0/(maxy-miny+1)
-
-		p = grass.feed_command('d.graph', color = color)
-		ofile = p.stdin
-
-		ifile = file(tmpfile, 'r')
-		for l in ifile:
-		    f = l.rstrip('\r\n').split(' ')
-		    x = float(f[0])
-		    y = float(f[1])
-		    ofile.write("icon + 0.1 %f %f\n" % ((x-minx+1) * kx, (y-miny+1) * ky))
-		ifile.close()
-
-		ofile.close()
-		p.wait()
+        for jloop, j in enumerate(layers):
+            if i != j and iloop <= jloop:
+                color = colors[0]
+                colors = colors[1:]
+                colors.append(color)
+                gcore.write_command('d.text', color=color, size=4, line=line,
+                                    stdin="%s %s" % (i, j))
+                line += 1
+
+                ofile = file(tmpfile, 'w')
+                gcore.run_command('r.stats', flags='cnA', input=(i, j),
+                                  stdout=ofile)
+                ofile.close()
+
+                ifile = file(tmpfile, 'r')
+                first = True
+                for l in ifile:
+                    f = l.rstrip('\r\n').split(' ')
+                    x = float(f[0])
+                    y = float(f[1])
+                    if first:
+                        minx = maxx = x
+                        miny = maxy = y
+                        first = False
+                    if minx > x:
+                        minx = x
+                    if maxx < x:
+                        maxx = x
+                    if miny > y:
+                        miny = y
+                    if maxy < y:
+                        maxy = y
+                ifile.close()
+
+                kx = 100.0 / (maxx - minx + 1)
+                ky = 100.0 / (maxy - miny + 1)
+
+                p = gcore.feed_command('d.graph', color=color)
+                ofile = p.stdin
+
+                ifile = file(tmpfile, 'r')
+                for l in ifile:
+                    f = l.rstrip('\r\n').split(' ')
+                    x = float(f[0])
+                    y = float(f[1])
+                    ofile.write("icon + 0.1 %f %f\n" % ((x - minx + 1) * kx,
+                                                        (y - miny + 1) * ky))
+                ifile.close()
+
+                ofile.close()
+                p.wait()
 
 
     try_remove(tmpfile)
     try_remove(tmpfile)
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gcore.parser()
     main()
     main()

+ 44 - 20
scripts/d.frame/d.frame.py

@@ -71,11 +71,15 @@ import sys
 from grass.script.core import parser, read_command, fatal, debug, run_command, gisenv, warning, parse_command
 from grass.script.core import parser, read_command, fatal, debug, run_command, gisenv, warning, parse_command
 
 
 # check if monitor is running
 # check if monitor is running
+
+
 def check_monitor():
 def check_monitor():
     return read_command('d.mon', flags='p', quiet=True).strip()
     return read_command('d.mon', flags='p', quiet=True).strip()
 
 
 # read monitor file and return list of lines
 # read monitor file and return list of lines
 # TODO: replace by d.info (see #2577)
 # TODO: replace by d.info (see #2577)
+
+
 def read_monitor_file(monitor, ftype='env'):
 def read_monitor_file(monitor, ftype='env'):
     mfile = check_monitor_file(monitor, ftype)
     mfile = check_monitor_file(monitor, ftype)
     try:
     try:
@@ -88,18 +92,22 @@ def read_monitor_file(monitor, ftype='env'):
         lines.append(line)
         lines.append(line)
 
 
     fd.close()
     fd.close()
-    
+
     return lines
     return lines
 
 
 # check if monitor file exists
 # check if monitor file exists
+
+
 def check_monitor_file(monitor, ftype='env'):
 def check_monitor_file(monitor, ftype='env'):
     mfile = parse_command('d.mon', flags='g').get(ftype, None)
     mfile = parse_command('d.mon', flags='g').get(ftype, None)
     if mfile is None or not os.path.isfile(mfile):
     if mfile is None or not os.path.isfile(mfile):
         fatal(_("Unable to get monitor info (no %s found)") % var)
         fatal(_("Unable to get monitor info (no %s found)") % var)
-    
+
     return mfile
     return mfile
 
 
 # write new monitor file
 # write new monitor file
+
+
 def write_monitor_file(monitor, lines, ftype='env'):
 def write_monitor_file(monitor, lines, ftype='env'):
     mfile = check_monitor_file(monitor, ftype)
     mfile = check_monitor_file(monitor, ftype)
 
 
@@ -112,19 +120,23 @@ def write_monitor_file(monitor, lines, ftype='env'):
     fd.close()
     fd.close()
 
 
 # remove all frames and erase screen
 # remove all frames and erase screen
+
+
 def erase(monitor):
 def erase(monitor):
     # remove frames
     # remove frames
     lines = []
     lines = []
     for line in read_monitor_file(monitor):
     for line in read_monitor_file(monitor):
         if 'FRAME' not in line:
         if 'FRAME' not in line:
             lines.append(line)
             lines.append(line)
-            
+
     write_monitor_file(monitor, lines)
     write_monitor_file(monitor, lines)
-    
+
     # erase screen
     # erase screen
     run_command('d.erase')
     run_command('d.erase')
 
 
 # find frame for given monitor
 # find frame for given monitor
+
+
 def find_frame(monitor, frame):
 def find_frame(monitor, frame):
     for line in read_monitor_file(monitor):
     for line in read_monitor_file(monitor):
         if 'FRAME' in line:
         if 'FRAME' in line:
@@ -134,6 +146,8 @@ def find_frame(monitor, frame):
     return False
     return False
 
 
 # print frames name(s) to stdout
 # print frames name(s) to stdout
+
+
 def print_frames(monitor, current_only=False, full=False):
 def print_frames(monitor, current_only=False, full=False):
     for line in read_monitor_file(monitor):
     for line in read_monitor_file(monitor):
         if 'FRAME' not in line:
         if 'FRAME' not in line:
@@ -146,10 +160,14 @@ def print_frames(monitor, current_only=False, full=False):
         sys.stdout.write('\n')
         sys.stdout.write('\n')
 
 
 # get frame name from line
 # get frame name from line
+
+
 def get_frame_name(line):
 def get_frame_name(line):
     return line.rstrip('\n').rsplit('#', 1)[1].strip(' ')
     return line.rstrip('\n').rsplit('#', 1)[1].strip(' ')
 
 
 # calculate position of the frame in percent
 # calculate position of the frame in percent
+
+
 def calculate_frame(frame, at, width, height):
 def calculate_frame(frame, at, width, height):
     try:
     try:
         b, t, l, r = map(float, at.split(','))
         b, t, l, r = map(float, at.split(','))
@@ -160,11 +178,13 @@ def calculate_frame(frame, at, width, height):
     bottom = height - (b / 100. * height)
     bottom = height - (b / 100. * height)
     left = l / 100. * width
     left = l / 100. * width
     right = r / 100. * width
     right = r / 100. * width
-    
+
     return 'GRASS_RENDER_FRAME=%d,%d,%d,%d # %s%s' % \
     return 'GRASS_RENDER_FRAME=%d,%d,%d,%d # %s%s' % \
         (top, bottom, left, right, frame, '\n')
         (top, bottom, left, right, frame, '\n')
-    
+
 # create new frame
 # create new frame
+
+
 def create_frame(monitor, frame, at, overwrite=False):
 def create_frame(monitor, frame, at, overwrite=False):
     lines = read_monitor_file(monitor)
     lines = read_monitor_file(monitor)
     # get width and height of the monitor
     # get width and height of the monitor
@@ -180,7 +200,7 @@ def create_frame(monitor, frame, at, overwrite=False):
 
 
     if width < 0 or height < 0:
     if width < 0 or height < 0:
         fatal(_("Invalid monitor size: %dx%d") % (width, height))
         fatal(_("Invalid monitor size: %dx%d") % (width, height))
-    
+
     if not overwrite:
     if not overwrite:
         lines.append(calculate_frame(frame, at, width, height))
         lines.append(calculate_frame(frame, at, width, height))
     else:
     else:
@@ -190,10 +210,12 @@ def create_frame(monitor, frame, at, overwrite=False):
                 continue
                 continue
             if get_frame_name(line) == frame:
             if get_frame_name(line) == frame:
                 lines[idx] = calculate_frame(frame, at, width, height)
                 lines[idx] = calculate_frame(frame, at, width, height)
-    
+
     write_monitor_file(monitor, lines)
     write_monitor_file(monitor, lines)
 
 
 # select existing frame
 # select existing frame
+
+
 def select_frame(monitor, frame):
 def select_frame(monitor, frame):
     lines = read_monitor_file(monitor)
     lines = read_monitor_file(monitor)
     for idx in range(len(lines)):
     for idx in range(len(lines)):
@@ -202,28 +224,29 @@ def select_frame(monitor, frame):
             continue
             continue
         if get_frame_name(line) == frame:
         if get_frame_name(line) == frame:
             if line.startswith('#'):
             if line.startswith('#'):
-                lines[idx] = line.lstrip('# ') # un-comment line
+                lines[idx] = line.lstrip('# ')  # un-comment line
         elif not line.startswith('#'):
         elif not line.startswith('#'):
-            lines[idx] = '# ' + line # comment-line
-    
+            lines[idx] = '# ' + line  # comment-line
+
     write_monitor_file(monitor, lines)
     write_monitor_file(monitor, lines)
-    
+
+
 def main():
 def main():
     # get currently selected monitor
     # get currently selected monitor
     monitor = check_monitor()
     monitor = check_monitor()
     if not monitor:
     if not monitor:
         fatal(_("No graphics device selected. Use d.mon to select graphics device."))
         fatal(_("No graphics device selected. Use d.mon to select graphics device."))
-    
+
     if flags['e']:
     if flags['e']:
         # remove frames and erase monitor and exit
         # remove frames and erase monitor and exit
         erase(monitor)
         erase(monitor)
         return
         return
-    
+
     if flags['p']:
     if flags['p']:
         # print current frame and exit
         # print current frame and exit
         print_frames(monitor, current_only=True)
         print_frames(monitor, current_only=True)
         return
         return
-        
+
     if flags['a']:
     if flags['a']:
         # print all frames including their position and exit
         # print all frames including their position and exit
         print_frames(monitor, current_only=False, full=True)
         print_frames(monitor, current_only=False, full=True)
@@ -245,12 +268,13 @@ def main():
             create_frame(monitor, options['frame'], options['at'], overwrite=True)
             create_frame(monitor, options['frame'], options['at'], overwrite=True)
         else:
         else:
             if options['at']:
             if options['at']:
-                warning(_("Frame <%s> already found. An existing frame can be overwritten by '%s' flag.") % \
-                        (options['frame'], "--overwrite"))
-    
-    # select givenframe 
+                warning(
+                    _("Frame <%s> already found. An existing frame can be overwritten by '%s' flag.") %
+                    (options['frame'], "--overwrite"))
+
+    # select givenframe
     select_frame(monitor, options['frame'])
     select_frame(monitor, options['frame'])
-            
+
 if __name__ == "__main__":
 if __name__ == "__main__":
     options, flags = parser()
     options, flags = parser()
     sys.exit(main())
     sys.exit(main())

+ 167 - 136
scripts/d.polar/d.polar.py

@@ -42,7 +42,6 @@
 #% description: Plot using Xgraph
 #% description: Plot using Xgraph
 #%end
 #%end
 
 
-import sys
 import os
 import os
 import string
 import string
 import types
 import types
@@ -51,34 +50,38 @@ import atexit
 import glob
 import glob
 import shutil
 import shutil
 from grass.script.utils import try_remove, basename
 from grass.script.utils import try_remove, basename
-from grass.script import core as grass
+from grass.script import core as gcore
+
 
 
 def cleanup():
 def cleanup():
     try_remove(tmp)
     try_remove(tmp)
     for f in glob.glob(tmp + '_*'):
     for f in glob.glob(tmp + '_*'):
-	try_remove(f)
+        try_remove(f)
+
 
 
 def plot_xgraph():
 def plot_xgraph():
     newline = ['\n']
     newline = ['\n']
-    p = grass.Popen(['xgraph'], stdin = grass.PIPE)
+    p = gcore.Popen(['xgraph'], stdin=gcore.PIPE)
     for point in sine_cosine_replic + newline + outercircle + newline + vector:
     for point in sine_cosine_replic + newline + outercircle + newline + vector:
-	if isinstance(point, types.TupleType):
-	    p.stdin.write("%f %f\n" % point)
-	else:
-	    p.stdin.write(point + '\n')
+        if isinstance(point, types.TupleType):
+            p.stdin.write("%f %f\n" % point)
+        else:
+            p.stdin.write(point + '\n')
     p.stdin.close()
     p.stdin.close()
     p.wait()
     p.wait()
 
 
+
 def plot_dgraph():
 def plot_dgraph():
-    # use d.info and d.frame to create a square frame in the center of the window.
-    s = grass.read_command('d.info', flags = 'd')
+    # use d.info and d.frame to create a square frame in the center of the
+    # window.
+    s = gcore.read_command('d.info', flags='d')
     f = s.split()
     f = s.split()
     frame_width = float(f[1])
     frame_width = float(f[1])
     frame_height = float(f[2])
     frame_height = float(f[2])
 
 
     # take shorter side as length of frame side
     # take shorter side as length of frame side
     min_side = min(frame_width, frame_height)
     min_side = min(frame_width, frame_height)
-    dx = (frame_width  - min_side) / 2
+    dx = (frame_width - min_side) / 2
     dy = (frame_height - min_side) / 2
     dy = (frame_height - min_side) / 2
 
 
     fl = dx
     fl = dx
@@ -94,32 +97,32 @@ def plot_dgraph():
     scaleval = ring * totalvalidnumber / totalnumber
     scaleval = ring * totalvalidnumber / totalnumber
 
 
     sine_cosine_replic_normalized = [
     sine_cosine_replic_normalized = [
-	((scaleval * p[0]/maxradius + 1)*50,
-	 (scaleval * p[1]/maxradius + 1)*50)
-	for p in sine_cosine_replic
-	if isinstance(p, types.TupleType)]
+        ((scaleval * p[0] / maxradius + 1) * 50,
+         (scaleval * p[1] / maxradius + 1) * 50)
+        for p in sine_cosine_replic if isinstance(p, types.TupleType)]
 
 
     # create circle
     # create circle
-    circle = [(50*(1 + ring * math.sin(math.radians(i))),
-	       50*(1 + ring * math.cos(math.radians(i))))
-	      for i in range(0, 361)]
+    circle = [(50 * (1 + ring * math.sin(math.radians(i))),
+               50 * (1 + ring * math.cos(math.radians(i))))
+              for i in range(0, 361)]
 
 
     # trend vector
     # trend vector
-    vect = [((scaleval * p[0]/maxradius + 1)*50,
-	     (scaleval * p[1]/maxradius + 1)*50)
-	    for p in vector[1:]]
+    vect = [((scaleval * p[0] / maxradius + 1) * 50,
+             (scaleval * p[1] / maxradius + 1) * 50)
+            for p in vector[1:]]
 
 
     # Possible TODOs:
     # Possible TODOs:
     # To fill data area with color, use BOTH d.graph's polyline and polygon commands.
     # To fill data area with color, use BOTH d.graph's polyline and polygon commands.
-    #  Using polygon alone gives a jagged boundary due to sampling technique (not a bug).
+    # Using polygon alone gives a jagged boundary due to sampling technique
+    # (not a bug).
 
 
     # plot it!
     # plot it!
     lines = [
     lines = [
-	# draw circle
-	#   mandatory when drawing proportional to non-square frame
-	"color 180:255:180",
-	"polyline"] + circle + [
-	# draw axes
+        # draw circle
+        #   mandatory when drawing proportional to non-square frame
+        "color 180:255:180",
+        "polyline"] + circle + [
+        # draw axes
         "color 180:180:180",
         "color 180:180:180",
         "width 0",
         "width 0",
         "move 0 50",
         "move 0 50",
@@ -127,16 +130,16 @@ def plot_dgraph():
         "move 50 0",
         "move 50 0",
         "draw 50 100",
         "draw 50 100",
 
 
-	# draw the goods
+        # draw the goods
         "color red",
         "color red",
         "width 0",
         "width 0",
         "polyline"] + sine_cosine_replic_normalized + [
         "polyline"] + sine_cosine_replic_normalized + [
-	# draw vector
+        # draw vector
         "color blue",
         "color blue",
         "width 3",
         "width 3",
         "polyline"] + vect + [
         "polyline"] + vect + [
 
 
-	# draw compass text
+        # draw compass text
         "color black",
         "color black",
         "width 2",
         "width 2",
         "size 10 10",
         "size 10 10",
@@ -149,7 +152,7 @@ def plot_dgraph():
         "move 97 51",
         "move 97 51",
         "text E",
         "text E",
 
 
-	# draw legend text
+        # draw legend text
         "width 0",
         "width 0",
         "size 10",
         "size 10",
         "color 0:180:0",
         "color 0:180:0",
@@ -161,20 +164,21 @@ def plot_dgraph():
         "color blue",
         "color blue",
         "move 0.5 90.5",
         "move 0.5 90.5",
         "text Avg. direction"
         "text Avg. direction"
-	]
+    ]
 
 
-    p = grass.feed_command('d.graph', env = tenv)
+    p = gcore.feed_command('d.graph', env=tenv)
     for point in lines:
     for point in lines:
-	if isinstance(point, types.TupleType):
-	    p.stdin.write("%f %f\n" % point)
-	else:
-	    p.stdin.write(point + '\n')
+        if isinstance(point, types.TupleType):
+            p.stdin.write("%f %f\n" % point)
+        else:
+            p.stdin.write(point + '\n')
     p.stdin.close()
     p.stdin.close()
     p.wait()
     p.wait()
 
 
+
 def plot_eps(psout):
 def plot_eps(psout):
     # EPS output (by M.Neteler and Bruno Caprile, ITC-irst)
     # EPS output (by M.Neteler and Bruno Caprile, ITC-irst)
-    grass.message(_("Generating %s ...") % psout)
+    gcore.message(_("Generating %s ...") % psout)
 
 
     outerradius = maxradius
     outerradius = maxradius
     epsscale = 0.1
     epsscale = 0.1
@@ -189,24 +193,24 @@ def plot_eps(psout):
     diagramfontsize = halfframe / 20
     diagramfontsize = halfframe / 20
     halfframe_2 = halfframe * 2
     halfframe_2 = halfframe * 2
 
 
-    averagedirectioncolor = 1 #(blue)
-    diagramcolor = 4 #(red)
-    circlecolor = 2 #(green)
-    axescolor = 0 #(black)
+    averagedirectioncolor = 1  # (blue)
+    diagramcolor = 4  # (red)
+    circlecolor = 2  # (green)
+    axescolor = 0  # (black)
 
 
     northjustification = 2
     northjustification = 2
     eastjustification = 6
     eastjustification = 6
     southjustification = 8
     southjustification = 8
     westjustification = 8
     westjustification = 8
 
 
-    northxshift = 1.02 * halfframe 
-    northyshift = 1.98 * halfframe 
-    eastxshift  = 1.98 * halfframe  
-    eastyshift  = 1.02 * halfframe  
-    southxshift = 1.02 * halfframe 
-    southyshift = 0.02 * halfframe 
-    westxshift  = 0.01 * halfframe  
-    westyshift  = 1.02 * halfframe  
+    northxshift = 1.02 * halfframe
+    northyshift = 1.98 * halfframe
+    eastxshift = 1.98 * halfframe
+    eastyshift = 1.02 * halfframe
+    southxshift = 1.02 * halfframe
+    southyshift = 0.02 * halfframe
+    westxshift = 0.01 * halfframe
+    westyshift = 1.02 * halfframe
 
 
     alldatastring = "all data (null included)"
     alldatastring = "all data (null included)"
     realdatastring = "real data angles"
     realdatastring = "real data angles"
@@ -220,7 +224,11 @@ def plot_eps(psout):
     ##########
     ##########
     outf = file(psout, 'w')
     outf = file(psout, 'w')
 
 
-    prolog = os.path.join(os.environ['GISBASE'], 'etc', 'd.polar', 'ps_defs.eps')
+    prolog = os.path.join(
+        os.environ['GISBASE'],
+        'etc',
+        'd.polar',
+        'ps_defs.eps')
     inf = file(prolog)
     inf = file(prolog)
     shutil.copyfileobj(inf, outf)
     shutil.copyfileobj(inf, outf)
     inf.close()
     inf.close()
@@ -254,20 +262,24 @@ newpath
                                         %% first point moveto, then lineto
                                         %% first point moveto, then lineto
 """)
 """)
     s = t.substitute(
     s = t.substitute(
-	AXESLINEWIDTH = axeslinewidth,
-	DIAGRAMFONTSIZE = diagramfontsize,
-	DIAGRAMLINEWIDTH = diagramlinewidth,
-	EPSSCALE = epsscale,
-	HALFFRAME = halfframe,
-	HALFFRAME_2 = halfframe_2
-	)
+        AXESLINEWIDTH=axeslinewidth,
+        DIAGRAMFONTSIZE=diagramfontsize,
+        DIAGRAMLINEWIDTH=diagramlinewidth,
+        EPSSCALE=epsscale,
+        HALFFRAME=halfframe,
+        HALFFRAME_2=halfframe_2
+    )
     outf.write(s)
     outf.write(s)
 
 
     sublength = len(outercircle) - 2
     sublength = len(outercircle) - 2
     (x, y) = outercircle[1]
     (x, y) = outercircle[1]
-    outf.write("%.2f %.2f moveto\n" % (x * scale + halfframe, y * scale + halfframe))
+    outf.write(
+        "%.2f %.2f moveto\n" %
+        (x * scale + halfframe, y * scale + halfframe))
     for x, y in outercircle[2:]:
     for x, y in outercircle[2:]:
-        outf.write("%.2f %.2f lineto\n" % (x * scale + halfframe, y * scale + halfframe))
+        outf.write(
+            "%.2f %.2f lineto\n" %
+            (x * scale + halfframe, y * scale + halfframe))
 
 
     t = string.Template("""
     t = string.Template("""
 stroke
 stroke
@@ -297,29 +309,33 @@ newpath
                                         %% first point moveto, then lineto
                                         %% first point moveto, then lineto
 """)
 """)
     s = t.substitute(
     s = t.substitute(
-	AXESFONTSIZE = axesfontsize,
-	DIAGRAMFONTSIZE = diagramfontsize,
-	DIAGRAMLINEWIDTH = diagramlinewidth,
-	EASTJUSTIFICATION = eastjustification,
-	EASTXSHIFT = eastxshift,
-	EASTYSHIFT = eastyshift,
-	NORTHJUSTIFICATION = northjustification,
-	NORTHXSHIFT = northxshift,
-	NORTHYSHIFT = northyshift,
-	SOUTHJUSTIFICATION = southjustification,
-	SOUTHXSHIFT = southxshift,
-	SOUTHYSHIFT = southyshift,
-	WESTJUSTIFICATION = westjustification,
-	WESTXSHIFT = westxshift,
-	WESTYSHIFT = westyshift
-	)
+        AXESFONTSIZE=axesfontsize,
+        DIAGRAMFONTSIZE=diagramfontsize,
+        DIAGRAMLINEWIDTH=diagramlinewidth,
+        EASTJUSTIFICATION=eastjustification,
+        EASTXSHIFT=eastxshift,
+        EASTYSHIFT=eastyshift,
+        NORTHJUSTIFICATION=northjustification,
+        NORTHXSHIFT=northxshift,
+        NORTHYSHIFT=northyshift,
+        SOUTHJUSTIFICATION=southjustification,
+        SOUTHXSHIFT=southxshift,
+        SOUTHYSHIFT=southyshift,
+        WESTJUSTIFICATION=westjustification,
+        WESTXSHIFT=westxshift,
+        WESTYSHIFT=westyshift
+    )
     outf.write(s)
     outf.write(s)
 
 
     sublength = len(sine_cosine_replic) - 2
     sublength = len(sine_cosine_replic) - 2
     (x, y) = sine_cosine_replic[1]
     (x, y) = sine_cosine_replic[1]
-    outf.write("%.2f %.2f moveto\n" % (x * scale + halfframe, y * scale + halfframe))
+    outf.write(
+        "%.2f %.2f moveto\n" %
+        (x * scale + halfframe, y * scale + halfframe))
     for x, y in sine_cosine_replic[2:]:
     for x, y in sine_cosine_replic[2:]:
-        outf.write("%.2f %.2f lineto\n" % (x * scale + halfframe, y * scale + halfframe))
+        outf.write(
+            "%.2f %.2f lineto\n" %
+            (x * scale + halfframe, y * scale + halfframe))
 
 
     t = string.Template("""
     t = string.Template("""
 stroke
 stroke
@@ -334,14 +350,18 @@ newpath
                                         %% coordinates of rescaled, translated average direction follow
                                         %% coordinates of rescaled, translated average direction follow
                                         %% first point moveto, second lineto
                                         %% first point moveto, second lineto
 """)
 """)
-    s = t.substitute(DIAGRAMLINEWIDTH = diagramlinewidth)
+    s = t.substitute(DIAGRAMLINEWIDTH=diagramlinewidth)
     outf.write(s)
     outf.write(s)
 
 
     sublength = len(vector) - 2
     sublength = len(vector) - 2
     (x, y) = vector[1]
     (x, y) = vector[1]
-    outf.write("%.2f %.2f moveto\n" % (x * scale + halfframe, y * scale + halfframe))
+    outf.write(
+        "%.2f %.2f moveto\n" %
+        (x * scale + halfframe, y * scale + halfframe))
     for x, y in vector[2:]:
     for x, y in vector[2:]:
-        outf.write("%.2f %.2f lineto\n" % (x * scale + halfframe, y * scale + halfframe))
+        outf.write(
+            "%.2f %.2f lineto\n" %
+            (x * scale + halfframe, y * scale + halfframe))
 
 
     t = string.Template("""
     t = string.Template("""
 stroke
 stroke
@@ -363,19 +383,20 @@ col1                                    %% colAVERAGE-DIRECTION-COLOR
 ($AVERAGEDIRECTIONSTRING) $LEGENDSX $AVERAGEDIRECTIONLEGENDY 4 just-string
 ($AVERAGEDIRECTIONSTRING) $LEGENDSX $AVERAGEDIRECTIONLEGENDY 4 just-string
 """)
 """)
     s = t.substitute(
     s = t.substitute(
-	ALLDATALEGENDY = alldatalegendy,
-	ALLDATASTRING = alldatastring,
-	AVERAGEDIRECTIONLEGENDY = averagedirectionlegendy,
-	AVERAGEDIRECTIONSTRING = averagedirectionstring,
-	LEGENDSX = legendsx,
-	REALDATALEGENDY = realdatalegendy,
-	REALDATASTRING = realdatastring
-	)
+        ALLDATALEGENDY=alldatalegendy,
+        ALLDATASTRING=alldatastring,
+        AVERAGEDIRECTIONLEGENDY=averagedirectionlegendy,
+        AVERAGEDIRECTIONSTRING=averagedirectionstring,
+        LEGENDSX=legendsx,
+        REALDATALEGENDY=realdatalegendy,
+        REALDATASTRING=realdatastring
+    )
     outf.write(s)
     outf.write(s)
 
 
     outf.close()
     outf.close()
 
 
-    grass.message(_("Done."))
+    gcore.message(_("Done."))
+
 
 
 def main():
 def main():
     global tmp
     global tmp
@@ -387,31 +408,33 @@ def main():
     eps = options['output']
     eps = options['output']
     xgraph = flags['x']
     xgraph = flags['x']
 
 
-    tmp = grass.tempfile()
+    tmp = gcore.tempfile()
 
 
     if eps and xgraph:
     if eps and xgraph:
-	grass.fatal(_("Please select only one output method"))
+        gcore.fatal(_("Please select only one output method"))
 
 
-    #### check if we have xgraph (if no EPS output requested)
-    if xgraph and not grass.find_program('xgraph'):
-	grass.fatal(_("xgraph required, please install first (www.xgraph.org)"))
+    # check if we have xgraph (if no EPS output requested)
+    if xgraph and not gcore.find_program('xgraph'):
+        gcore.fatal(
+            _("xgraph required, please install first (www.xgraph.org)"))
 
 
     #################################
     #################################
     # this file contains everthing:
     # this file contains everthing:
     rawfile = tmp + "_raw"
     rawfile = tmp + "_raw"
     rawf = file(rawfile, 'w')
     rawf = file(rawfile, 'w')
-    grass.run_command('r.stats', flags = '1', input = map, stdout = rawf)
+    gcore.run_command('r.stats', flags='1', input=map, stdout=rawf)
     rawf.close()
     rawf.close()
 
 
     rawf = file(rawfile)
     rawf = file(rawfile)
     totalnumber = 0
     totalnumber = 0
     for line in rawf:
     for line in rawf:
-	totalnumber += 1
+        totalnumber += 1
     rawf.close()
     rawf.close()
 
 
-    grass.message(_("Calculating statistics for polar diagram... (be patient)"))
+    gcore.message(
+        _("Calculating statistics for polar diagram... (be patient)"))
 
 
-    #wipe out NULL data and undef data if defined by user
+    # wipe out NULL data and undef data if defined by user
     # - generate degree binned to integer, eliminate NO DATA (NULL):
     # - generate degree binned to integer, eliminate NO DATA (NULL):
     # change 360 to 0 to close polar diagram:
     # change 360 to 0 to close polar diagram:
     rawf = file(rawfile)
     rawf = file(rawfile)
@@ -420,26 +443,26 @@ def main():
     sumsin = 0
     sumsin = 0
     freq = {}
     freq = {}
     for line in rawf:
     for line in rawf:
-	line = line.rstrip('\r\n')
-	if line in ['*', undef]:
-	    continue
-	nvals += 1
-	x = float(line)
-	rx = math.radians(x)
-	sumcos += math.cos(rx)
-	sumsin += math.sin(rx)
-	ix = round(x)
-	if ix == 360:
-	    ix = 0
-	if ix in freq:
-	    freq[ix] += 1
-	else:
-	    freq[ix] = 1
+        line = line.rstrip('\r\n')
+        if line in ['*', undef]:
+            continue
+        nvals += 1
+        x = float(line)
+        rx = math.radians(x)
+        sumcos += math.cos(rx)
+        sumsin += math.sin(rx)
+        ix = round(x)
+        if ix == 360:
+            ix = 0
+        if ix in freq:
+            freq[ix] += 1
+        else:
+            freq[ix] = 1
     rawf.close()
     rawf.close()
 
 
     totalvalidnumber = nvals
     totalvalidnumber = nvals
     if totalvalidnumber == 0:
     if totalvalidnumber == 0:
-	grass.fatal(_("No data pixel found"))
+        gcore.fatal(_("No data pixel found"))
 
 
     #################################
     #################################
     # unit vector on raw data converted to radians without no data:
     # unit vector on raw data converted to radians without no data:
@@ -449,9 +472,8 @@ def main():
     #################################
     #################################
     # how many are there?:
     # how many are there?:
 
 
-    occurrences = [(math.radians(x), freq[x]) for x in freq]
-    occurrences.sort()
-    
+    occurrences = sorted([(math.radians(x), freq[x]) for x in freq])
+
     # find the maximum value
     # find the maximum value
     maxradius = max([f for a, f in occurrences])
     maxradius = max([f for a, f in occurrences])
 
 
@@ -461,14 +483,14 @@ def main():
     sine_cosine_replic = ['"Real data angles'] + sine_cosine + sine_cosine[0:1]
     sine_cosine_replic = ['"Real data angles'] + sine_cosine + sine_cosine[0:1]
 
 
     if eps or xgraph:
     if eps or xgraph:
-	outercircle = []
-	outercircle.append('"All Data incl. NULLs')
-	scale = 1.0 * totalnumber / totalvalidnumber * maxradius
-	for i in range(0, 361):
-	    a = math.radians(i)
-	    x = math.cos(a) * scale
-	    y = math.sin(a) * scale
-	    outercircle.append((x, y))
+        outercircle = []
+        outercircle.append('"All Data incl. NULLs')
+        scale = 1.0 * totalnumber / totalvalidnumber * maxradius
+        for i in range(0, 361):
+            a = math.radians(i)
+            x = math.cos(a) * scale
+            y = math.sin(a) * scale
+            outercircle.append((x, y))
 
 
     # fix vector length to become visible (x? of $MAXRADIUS):
     # fix vector length to become visible (x? of $MAXRADIUS):
     vector = []
     vector = []
@@ -481,19 +503,28 @@ def main():
     # Now output:
     # Now output:
 
 
     if eps:
     if eps:
-	psout = basename(eps, 'eps') + '.eps'
-	plot_eps(psout)
+        psout = basename(eps, 'eps') + '.eps'
+        plot_eps(psout)
     elif xgraph:
     elif xgraph:
-	plot_xgraph()
+        plot_xgraph()
     else:
     else:
-	plot_dgraph()
-
-    grass.message(_("Average vector:"))
-    grass.message(_("direction: %.1f degrees CCW from East") % math.degrees(math.atan2(unitvector[1], unitvector[0])))
-    grass.message(_("magnitude: %.1f percent of fullscale") % (100 * math.hypot(unitvector[0], unitvector[1])))
+        plot_dgraph()
+
+    gcore.message(_("Average vector:"))
+    gcore.message(
+        _("direction: %.1f degrees CCW from East") %
+        math.degrees(
+            math.atan2(
+                unitvector[1],
+                unitvector[0])))
+    gcore.message(
+        _("magnitude: %.1f percent of fullscale") %
+        (100 *
+         math.hypot(
+             unitvector[0],
+             unitvector[1])))
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gcore.parser()
     atexit.register(cleanup)
     atexit.register(cleanup)
     main()
     main()
-

파일 크기가 너무 크기때문에 변경 상태를 표시하지 않습니다.
+ 474 - 446
scripts/d.rast.edit/d.rast.edit.py


+ 4 - 2
scripts/d.rast.leg/d.rast.leg.py

@@ -125,8 +125,10 @@ def main():
     ncats = len(cats.strip().split('\n'))
     ncats = len(cats.strip().split('\n'))
 
 
     # Only need to adjust legend size if number of categories is between 1 and 10
     # Only need to adjust legend size if number of categories is between 1 and 10
-    if ncats < 2: ncats = 2
-    if ncats > 10: ncats = 10
+    if ncats < 2:
+        ncats = 2
+    if ncats > 10:
+        ncats = 10
 
 
     VSpacing = (100 - (ncats * 10) + 10)
     VSpacing = (100 - (ncats * 10) + 10)
 
 

+ 10 - 9
scripts/d.redraw/d.redraw.py

@@ -26,6 +26,7 @@ import sys
 from grass.script import core as grass
 from grass.script import core as grass
 from grass.script.utils import split
 from grass.script.utils import split
 
 
+
 def main():
 def main():
     mon = grass.gisenv().get('MONITOR', None)
     mon = grass.gisenv().get('MONITOR', None)
     if not mon:
     if not mon:
@@ -38,25 +39,25 @@ def main():
     try:
     try:
         fd = open(monCmd, 'r')
         fd = open(monCmd, 'r')
         cmdList = fd.readlines()
         cmdList = fd.readlines()
-        
+
         grass.run_command('d.erase')
         grass.run_command('d.erase')
-        
+
         for cmd in cmdList:
         for cmd in cmdList:
             grass.call(split(cmd))
             grass.call(split(cmd))
     except IOError as e:
     except IOError as e:
-        grass.fatal(_("Unable to open file '%s' for reading. Details: %s") % \
-                        (monCmd, e))
-    
+        grass.fatal(_("Unable to open file '%s' for reading. Details: %s") %
+                    (monCmd, e))
+
     fd.close()
     fd.close()
-    
+
     # restore cmd file
     # restore cmd file
     try:
     try:
         fd = open(monCmd, "w")
         fd = open(monCmd, "w")
         fd.writelines(cmdList)
         fd.writelines(cmdList)
     except IOError as e:
     except IOError as e:
-        grass.fatal(_("Unable to open file '%s' for writing. Details: %s") % \
-                        (monCmd, e))
-    
+        grass.fatal(_("Unable to open file '%s' for writing. Details: %s") %
+                    (monCmd, e))
+
     return 0
     return 0
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":

+ 44 - 43
scripts/db.dropcolumn/db.dropcolumn.py

@@ -5,7 +5,7 @@
 # MODULE:       db.dropcolumn
 # MODULE:       db.dropcolumn
 # AUTHOR(S):   	Markus Neteler
 # AUTHOR(S):   	Markus Neteler
 #               Converted to Python by Glynn Clements
 #               Converted to Python by Glynn Clements
-# PURPOSE:      Interface to db.execute to drop a column from an 
+# PURPOSE:      Interface to db.execute to drop a column from an
 #               attribute table
 #               attribute table
 #               - with special trick for SQLite
 #               - with special trick for SQLite
 # COPYRIGHT:    (C) 2007, 2012 by Markus Neteler and the GRASS Development Team
 # COPYRIGHT:    (C) 2007, 2012 by Markus Neteler and the GRASS Development Team
@@ -36,10 +36,10 @@
 #%end
 #%end
 
 
 import sys
 import sys
-import os
 import string
 import string
-import grass.script as grass
+
 from grass.exceptions import CalledModuleError
 from grass.exceptions import CalledModuleError
+import grass.script as gscript
 
 
 
 
 def main():
 def main():
@@ -48,66 +48,67 @@ def main():
     force = flags['f']
     force = flags['f']
 
 
     # check if DB parameters are set, and if not set them.
     # check if DB parameters are set, and if not set them.
-    grass.run_command('db.connect', flags = 'c')
+    gscript.run_command('db.connect', flags='c')
 
 
-    kv = grass.db_connection()
+    kv = gscript.db_connection()
     database = kv['database']
     database = kv['database']
     driver = kv['driver']
     driver = kv['driver']
     # schema needed for PG?
     # schema needed for PG?
 
 
     if force:
     if force:
-	grass.message(_("Forcing ..."))
+        gscript.message(_("Forcing ..."))
 
 
     if column == "cat":
     if column == "cat":
-	grass.warning(_("Deleting <%s> column which may be needed to keep table connected to a vector map") % column)
+        gscript.warning(_("Deleting <%s> column which may be needed to keep "
+                          "table connected to a vector map") % column)
 
 
-    cols = [f[0] for f in grass.db_describe(table)['cols']]
+    cols = [f[0] for f in gscript.db_describe(table)['cols']]
     if column not in cols:
     if column not in cols:
-	grass.fatal(_("Column <%s> not found in table") % column)
+        gscript.fatal(_("Column <%s> not found in table") % column)
 
 
     if not force:
     if not force:
-	grass.message(_("Column <%s> would be deleted.") % column)
-	grass.message("")
-	grass.message(_("You must use the force flag (-f) to actually remove it. Exiting."))
-	return 0
+        gscript.message(_("Column <%s> would be deleted.") % column)
+        gscript.message("")
+        gscript.message(_("You must use the force flag (-f) to actually "
+                          "remove it. Exiting."))
+        return 0
 
 
     if driver == "sqlite":
     if driver == "sqlite":
-	#echo "Using special trick for SQLite"
-	# http://www.sqlite.org/faq.html#q13
-	colnames = []
-	coltypes = []
-	for f in grass.db_describe(table)['cols']:
-	    if f[0] == column:
-		continue
-	    colnames.append(f[0])
-	    coltypes.append("%s %s" % (f[0], f[1]))
-
-	colnames = ", ".join(colnames)
-	coltypes = ", ".join(coltypes)
-
-	cmds = [
-	    "BEGIN TRANSACTION",
-	    "CREATE TEMPORARY TABLE ${table}_backup(${coldef})",
-	    "INSERT INTO ${table}_backup SELECT ${colnames} FROM ${table}",
-	    "DROP TABLE ${table}",
-	    "CREATE TABLE ${table}(${coldef})",
-	    "INSERT INTO ${table} SELECT ${colnames} FROM ${table}_backup",
-	    "DROP TABLE ${table}_backup",
-	    "COMMIT"
-	    ]
-	tmpl = string.Template(';\n'.join(cmds))
-	sql = tmpl.substitute(table = table, coldef = coltypes, colnames = colnames)
+        # echo "Using special trick for SQLite"
+        # http://www.sqlite.org/faq.html#q13
+        colnames = []
+        coltypes = []
+        for f in gscript.db_describe(table)['cols']:
+            if f[0] != column:
+                colnames.append(f[0])
+                coltypes.append("%s %s" % (f[0], f[1]))
+
+        colnames = ", ".join(colnames)
+        coltypes = ", ".join(coltypes)
+
+        cmds = [
+            "BEGIN TRANSACTION",
+            "CREATE TEMPORARY TABLE ${table}_backup(${coldef})",
+            "INSERT INTO ${table}_backup SELECT ${colnames} FROM ${table}",
+            "DROP TABLE ${table}",
+            "CREATE TABLE ${table}(${coldef})",
+            "INSERT INTO ${table} SELECT ${colnames} FROM ${table}_backup",
+            "DROP TABLE ${table}_backup",
+            "COMMIT"
+        ]
+        tmpl = string.Template(';\n'.join(cmds))
+        sql = tmpl.substitute(table=table, coldef=coltypes, colnames=colnames)
     else:
     else:
-	sql = "ALTER TABLE %s DROP COLUMN %s" % (table, column)
+        sql = "ALTER TABLE %s DROP COLUMN %s" % (table, column)
 
 
     try:
     try:
-        grass.write_command('db.execute', input = '-', database = database,
-                               driver = driver, stdin = sql)
+        gscript.write_command('db.execute', input='-', database=database,
+                              driver=driver, stdin=sql)
     except CalledModuleError:
     except CalledModuleError:
-        grass.fatal(_("Cannot continue (problem deleting column)"))
+        gscript.fatal(_("Cannot continue (problem deleting column)"))
 
 
     return 0
     return 0
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     sys.exit(main())
     sys.exit(main())

+ 31 - 29
scripts/db.in.ogr/db.in.ogr.py

@@ -72,74 +72,76 @@ def main():
     mapset = grass.gisenv()['MAPSET']
     mapset = grass.gisenv()['MAPSET']
 
 
     if db_table:
     if db_table:
-	input = db_table
+        input = db_table
 
 
     if not output:
     if not output:
-	tmpname = input.replace('.', '_')
-	output = grass.basename(tmpname)
+        tmpname = input.replace('.', '_')
+        output = grass.basename(tmpname)
 
 
     # check if table exists
     # check if table exists
     try:
     try:
         nuldev = file(os.devnull, 'w+')
         nuldev = file(os.devnull, 'w+')
-        s = grass.read_command('db.tables', flags = 'p', quiet=True, stderr=nuldev)
+        s = grass.read_command('db.tables', flags='p', quiet=True, stderr=nuldev)
         nuldev.close()
         nuldev.close()
     except CalledModuleError:
     except CalledModuleError:
         # check connection parameters, set if uninitialized
         # check connection parameters, set if uninitialized
         grass.read_command('db.connect', flags='c')
         grass.read_command('db.connect', flags='c')
-        s = grass.read_command('db.tables', flags = 'p', quiet=True)
-    
+        s = grass.read_command('db.tables', flags='p', quiet=True)
+
     for l in s.splitlines():
     for l in s.splitlines():
         if l == output:
         if l == output:
             if grass.overwrite():
             if grass.overwrite():
-                grass.warning(_("Table <%s> already exists and will be overwritten") % output)
-                grass.write_command('db.execute', input = '-', stdin = "DROP TABLE %s" % output)
+                grass.warning(_("Table <%s> already exists and will be "
+                                "overwritten") % output)
+                grass.write_command('db.execute', input='-',
+                                    stdin="DROP TABLE %s" % output)
                 break
                 break
             else:
             else:
                 grass.fatal(_("Table <%s> already exists") % output)
                 grass.fatal(_("Table <%s> already exists") % output)
-                
+
     # treat DB as real vector map...
     # treat DB as real vector map...
-    if db_table:
-	layer = db_table
-    else:
-	layer = None
+    layer = db_table if db_table else None
 
 
     vopts = {}
     vopts = {}
     if options['encoding']:
     if options['encoding']:
         vopts['encoding'] = options['encoding']
         vopts['encoding'] = options['encoding']
-    
+
     try:
     try:
         grass.run_command('v.in.ogr', flags='o', input=input, output=output,
         grass.run_command('v.in.ogr', flags='o', input=input, output=output,
                           layer=layer, quiet=True, **vopts)
                           layer=layer, quiet=True, **vopts)
     except CalledModuleError:
     except CalledModuleError:
         if db_table:
         if db_table:
-            grass.fatal(_("Input table <%s> not found or not readable") % input)
+            grass.fatal(
+                _("Input table <%s> not found or not readable") %
+                input)
         else:
         else:
             grass.fatal(_("Input DSN <%s> not found or not readable") % input)
             grass.fatal(_("Input DSN <%s> not found or not readable") % input)
 
 
     # rename ID col if requested from cat to new name
     # rename ID col if requested from cat to new name
     if key:
     if key:
-	grass.write_command('db.execute', quiet = True,
-                          input = '-', 
-			  stdin = "ALTER TABLE %s ADD COLUMN %s integer" % (output, key) )
-	grass.write_command('db.execute', quiet = True,
-                          input = '-', 
-			  stdin = "UPDATE %s SET %s=cat" % (output, key) )
+        grass.write_command('db.execute', quiet=True, input='-',
+                            stdin="ALTER TABLE %s ADD COLUMN %s integer" %
+                                  (output, key))
+        grass.write_command('db.execute', quiet=True, input='-',
+                            stdin="UPDATE %s SET %s=cat" % (output, key))
 
 
     # ... and immediately drop the empty geometry
     # ... and immediately drop the empty geometry
-    vectfile = grass.find_file(output, element = 'vector', mapset = mapset)['file']
+    vectfile = grass.find_file(output, element='vector', mapset=mapset)['file']
     if not vectfile:
     if not vectfile:
-	grass.fatal(_("Something went wrong. Should not happen"))
+        grass.fatal(_("Something went wrong. Should not happen"))
     else:
     else:
-	# remove the vector part
-	grass.run_command('v.db.connect', quiet = True, map = output, layer = '1', flags = 'd')
-	grass.run_command('g.remove', flags = 'f', quiet = True, type = 'vector', name = output)
+        # remove the vector part
+        grass.run_command('v.db.connect', quiet=True, map=output, layer='1',
+                          flags='d')
+        grass.run_command('g.remove', flags='f', quiet=True, type='vector',
+                          name=output)
 
 
     # get rid of superfluous auto-added cat column (and cat_ if present)
     # get rid of superfluous auto-added cat column (and cat_ if present)
     nuldev = file(os.devnull, 'w+')
     nuldev = file(os.devnull, 'w+')
-    grass.run_command('db.dropcolumn', quiet = True, flags = 'f', table = output,
-		      column = 'cat', stdout = nuldev, stderr = nuldev)
+    grass.run_command('db.dropcolumn', quiet=True, flags='f', table=output,
+                      column='cat', stdout=nuldev, stderr=nuldev)
     nuldev.close()
     nuldev.close()
-    
+
     records = grass.db_describe(output)['nrows']
     records = grass.db_describe(output)['nrows']
     grass.message(_("Imported table <%s> with %d rows") % (output, records))
     grass.message(_("Imported table <%s> with %d rows") % (output, records))
 
 

+ 28 - 30
scripts/db.out.ogr/db.out.ogr.py

@@ -54,10 +54,10 @@
 #% required: no
 #% required: no
 #%end
 #%end
 
 
-import sys
 import os
 import os
+
 from grass.script.utils import try_remove, basename
 from grass.script.utils import try_remove, basename
-from grass.script import core as grass
+from grass.script import core as gcore
 from grass.exceptions import CalledModuleError
 from grass.exceptions import CalledModuleError
 
 
 
 
@@ -69,54 +69,52 @@ def main():
     table = options['table']
     table = options['table']
 
 
     if format.lower() == 'dbf':
     if format.lower() == 'dbf':
-	format = "ESRI_Shapefile"
+        format = "ESRI_Shapefile"
 
 
     if format.lower() == 'csv':
     if format.lower() == 'csv':
-	olayer = basename(output, 'csv')
+        olayer = basename(output, 'csv')
     else:
     else:
-	olayer = None
+        olayer = None
 
 
-    #is there a simpler way of testing for --overwrite?
+    # is there a simpler way of testing for --overwrite?
     dbffile = input + '.dbf'
     dbffile = input + '.dbf'
-    if os.path.exists(dbffile) and not grass.overwrite():
-	grass.fatal(_("File <%s> already exists") % dbffile)
+    if os.path.exists(dbffile) and not gcore.overwrite():
+        gcore.fatal(_("File <%s> already exists") % dbffile)
 
 
     if olayer:
     if olayer:
         try:
         try:
-            grass.run_command('v.out.ogr', quiet=True, input=input, layer=layer,
-                              output=output,
-                              format=format, type='point,line,area',
-                              olayer=olayer)
+            gcore.run_command('v.out.ogr', quiet=True, input=input,
+                              layer=layer, output=output, format=format,
+                              type='point,line,area', olayer=olayer)
         except CalledModuleError:
         except CalledModuleError:
-            grass.fatal(_("Module <%s> failed") % 'v.out.ogr')
+            gcore.fatal(_("Module <%s> failed") % 'v.out.ogr')
 
 
     else:
     else:
         try:
         try:
-            grass.run_command('v.out.ogr', quiet=True, input=input,
+            gcore.run_command('v.out.ogr', quiet=True, input=input,
                               layer=layer, output=output,
                               layer=layer, output=output,
                               format=format, type='point,line,area')
                               format=format, type='point,line,area')
         except CalledModuleError:
         except CalledModuleError:
-            grass.fatal(_("Module <%s> failed") % 'v.out.ogr')
+            gcore.fatal(_("Module <%s> failed") % 'v.out.ogr')
 
 
     if format == "ESRI_Shapefile":
     if format == "ESRI_Shapefile":
-	exts = ['shp', 'shx', 'prj']
-	if output.endswith('.dbf'):
-	    outname = basename(output, 'dbf')
-	    for ext in exts:
-		try_remove("%s.%s" % (outname, ext))
-	    outname += '.dbf'
-	else:
-	    for ext in exts:
-		try_remove(os.path.join(output, "%s.%s" % (input, ext)))
-	    outname = os.path.join(output, input + ".dbf")
+        exts = ['shp', 'shx', 'prj']
+        if output.endswith('.dbf'):
+            outname = basename(output, 'dbf')
+            for ext in exts:
+                try_remove("%s.%s" % (outname, ext))
+            outname += '.dbf'
+        else:
+            for ext in exts:
+                try_remove(os.path.join(output, "%s.%s" % (input, ext)))
+            outname = os.path.join(output, input + ".dbf")
     elif format.lower() == 'csv':
     elif format.lower() == 'csv':
-	outname = output + '.csv'
+        outname = output + '.csv'
     else:
     else:
-	outname = input
+        outname = input
 
 
-    grass.message(_("Exported table <%s>") % outname)
+    gcore.message(_("Exported table <%s>") % outname)
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gcore.parser()
     main()
     main()
-

+ 31 - 30
scripts/db.test/db.test.py

@@ -28,61 +28,62 @@
 
 
 import sys
 import sys
 import os
 import os
-from grass.script import core as grass
+
+from grass.script import core as gcore
 from grass.script import db as grassdb
 from grass.script import db as grassdb
 from grass.exceptions import CalledModuleError
 from grass.exceptions import CalledModuleError
 
 
+
 def main():
 def main():
     test_file = options['test']
     test_file = options['test']
 
 
-    expected = grass.tempfile()
-    result = grass.tempfile()
+    expected = gcore.tempfile()
+    result = gcore.tempfile()
 
 
     dbconn = grassdb.db_connection()
     dbconn = grassdb.db_connection()
-    grass.message(_("Using DB driver: %s") % dbconn['driver'])
+    gcore.message(_("Using DB driver: %s") % dbconn['driver'])
 
 
     infile = os.path.join(os.environ['GISBASE'], 'etc', 'db.test', test_file)
     infile = os.path.join(os.environ['GISBASE'], 'etc', 'db.test', test_file)
     inf = file(infile)
     inf = file(infile)
 
 
     while True:
     while True:
-	type = inf.readline()
-	if not type:
-	    break
-	type = type.rstrip('\r\n')
-
-	sql = inf.readline().rstrip('\r\n')
-	sys.stdout.write(sql + '\n')
+        type = inf.readline()
+        if not type:
+            break
+        type = type.rstrip('\r\n')
 
 
-	# Copy expected result to temp file
+        sql = inf.readline().rstrip('\r\n')
+        sys.stdout.write(sql + '\n')
 
 
+        # Copy expected result to temp file
         try:
         try:
             if type == 'X':
             if type == 'X':
-                grass.write_command('db.execute', input = '-', stdin = sql + '\n')
+                gcore.write_command('db.execute', input='-', stdin=sql + '\n')
             else:
             else:
                 resf = file(result, 'w')
                 resf = file(result, 'w')
-                grass.write_command('db.select', input = '-', flags = 'c', stdin = sql + '\n', stdout = resf)
+                gcore.write_command('db.select', input='-', flags='c',
+                                    stdin=sql + '\n', stdout=resf)
                 resf.close()
                 resf.close()
 
 
         except CalledModuleError:
         except CalledModuleError:
-            grass.error("EXECUTE: ******** ERROR ********")
+            gcore.error("EXECUTE: ******** ERROR ********")
         else:
         else:
-            grass.message(_("EXECUTE: OK"))
+            gcore.message(_("EXECUTE: OK"))
 
 
-	expf = file(expected, 'w')
-	while True:
-	    res = inf.readline().rstrip('\r\n')
-	    if not res:
-		break
-	    expf.write(res + '\n')
-	expf.close()
+        expf = file(expected, 'w')
+        while True:
+            res = inf.readline().rstrip('\r\n')
+            if not res:
+                break
+            expf.write(res + '\n')
+        expf.close()
 
 
-	if type == 'S':
-	    if grass.call(['diff', result, expected]) != 0:
-		grass.error("RESULT: ******** ERROR ********")
-	    else:
-		grass.message(_("RESULT: OK"))
+        if type == 'S':
+            if gcore.call(['diff', result, expected]) != 0:
+                gcore.error("RESULT: ******** ERROR ********")
+            else:
+                gcore.message(_("RESULT: OK"))
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gcore.parser()
     main()
     main()
-

+ 93 - 60
scripts/db.univar/db.univar.py

@@ -56,25 +56,26 @@
 #%end
 #%end
 
 
 import sys
 import sys
-import os
 import atexit
 import atexit
 import math
 import math
 
 
-import grass.script as grass 
+import grass.script as gscript
+
 
 
 def cleanup():
 def cleanup():
     for ext in ['', '.sort']:
     for ext in ['', '.sort']:
-        grass.try_remove(tmp + ext)
+        gscript.try_remove(tmp + ext)
+
 
 
 def sortfile(infile, outfile):
 def sortfile(infile, outfile):
     inf = file(infile, 'r')
     inf = file(infile, 'r')
     outf = file(outfile, 'w')
     outf = file(outfile, 'w')
 
 
-    if grass.find_program('sort', '--help'):
-        grass.run_command('sort', flags = 'n', stdin = inf, stdout = outf)
+    if gscript.find_program('sort', '--help'):
+        gscript.run_command('sort', flags='n', stdin=inf, stdout=outf)
     else:
     else:
         # FIXME: we need a large-file sorting function
         # FIXME: we need a large-file sorting function
-        grass.warning(_("'sort' not found: sorting in memory"))
+        gscript.warning(_("'sort' not found: sorting in memory"))
         lines = inf.readlines()
         lines = inf.readlines()
         for i in range(len(lines)):
         for i in range(len(lines)):
             lines[i] = float(lines[i].rstrip('\r\n'))
             lines[i] = float(lines[i].rstrip('\r\n'))
@@ -85,9 +86,10 @@ def sortfile(infile, outfile):
     inf.close()
     inf.close()
     outf.close()
     outf.close()
 
 
+
 def main():
 def main():
     global tmp
     global tmp
-    tmp = grass.tempfile()
+    tmp = gscript.tempfile()
 
 
     extend = flags['e']
     extend = flags['e']
     shellstyle = flags['g']
     shellstyle = flags['g']
@@ -100,21 +102,22 @@ def main():
 
 
     perc = [float(p) for p in perc.split(',')]
     perc = [float(p) for p in perc.split(',')]
 
 
-    desc_table = grass.db_describe(table, database=database, driver=driver)
+    desc_table = gscript.db_describe(table, database=database, driver=driver)
     if not desc_table:
     if not desc_table:
-        grass.fatal(_("Unable to describe table <%s>") % table)
+        gscript.fatal(_("Unable to describe table <%s>") % table)
     found = False
     found = False
     for cname, ctype, cwidth in desc_table['cols']:
     for cname, ctype, cwidth in desc_table['cols']:
         if cname == column:
         if cname == column:
             found = True
             found = True
             if ctype not in ('INTEGER', 'DOUBLE PRECISION'):
             if ctype not in ('INTEGER', 'DOUBLE PRECISION'):
-                grass.fatal(_("Column <%s> is not numeric") % cname)
+                gscript.fatal(_("Column <%s> is not numeric") % cname)
     if not found:
     if not found:
-        grass.fatal(_("Column <%s> not found in table <%s>") % (column, table))
+        gscript.fatal(_("Column <%s> not found in table <%s>") % (column, table))
 
 
     if not shellstyle:
     if not shellstyle:
-        grass.verbose(_("Calculation for column <%s> of table <%s>...") % (column, table))
-        grass.message(_("Reading column values..."))
+        gscript.verbose(_("Calculation for column <%s> of table <%s>..."
+                          ) % (column, table))
+        gscript.message(_("Reading column values..."))
 
 
     sql = "SELECT %s FROM %s" % (column, table)
     sql = "SELECT %s FROM %s" % (column, table)
     if where:
     if where:
@@ -127,20 +130,20 @@ def main():
         driver = None
         driver = None
 
 
     tmpf = file(tmp, 'w')
     tmpf = file(tmp, 'w')
-    grass.run_command('db.select', flags = 'c', table = table,
-        database = database, driver = driver, sql = sql,
-        stdout = tmpf)
+    gscript.run_command('db.select', flags='c', table=table,
+                        database=database, driver=driver, sql=sql,
+                        stdout=tmpf)
     tmpf.close()
     tmpf.close()
 
 
     # check if result is empty
     # check if result is empty
     tmpf = file(tmp)
     tmpf = file(tmp)
     if tmpf.read(1) == '':
     if tmpf.read(1) == '':
-        grass.fatal(_("Table <%s> contains no data.") % table)
+        gscript.fatal(_("Table <%s> contains no data.") % table)
         tmpf.close()
         tmpf.close()
 
 
     # calculate statistics
     # calculate statistics
     if not shellstyle:
     if not shellstyle:
-        grass.verbose(_("Calculating statistics..."))
+        gscript.verbose(_("Calculating statistics..."))
 
 
     N = 0
     N = 0
     sum = 0.0
     sum = 0.0
@@ -151,8 +154,8 @@ def main():
 
 
     tmpf = file(tmp)
     tmpf = file(tmp)
     for line in tmpf:
     for line in tmpf:
-	if len(line.rstrip('\r\n')) == 0:
-	    continue
+        if len(line.rstrip('\r\n')) == 0:
+            continue
         x = float(line.rstrip('\r\n'))
         x = float(line.rstrip('\r\n'))
         N += 1
         N += 1
         sum += x
         sum += x
@@ -163,30 +166,43 @@ def main():
     tmpf.close()
     tmpf.close()
 
 
     if N <= 0:
     if N <= 0:
-        grass.fatal(_("No non-null values found"))
+        gscript.fatal(_("No non-null values found"))
 
 
     if not shellstyle:
     if not shellstyle:
-        sys.stdout.write("Number of values: %d\n"% N)
-        sys.stdout.write("Minimum: %.15g\n"% minv)
-        sys.stdout.write("Maximum: %.15g\n"% maxv)
-        sys.stdout.write("Range: %.15g\n"% (maxv - minv))
-        sys.stdout.write("Mean: %.15g\n"% (sum/N))
-        sys.stdout.write("Arithmetic mean of absolute values: %.15g\n"% (sum3/N))
-        sys.stdout.write("Variance: %.15g\n"% ((sum2 - sum*sum/N)/N))
-        sys.stdout.write("Standard deviation: %.15g\n"% (math.sqrt((sum2 - sum*sum/N)/N)))
-        sys.stdout.write("Coefficient of variation: %.15g\n"% ((math.sqrt((sum2 - sum*sum/N)/N))/(math.sqrt(sum*sum)/N)))
-        sys.stdout.write("Sum: %.15g\n"% sum)
+        sys.stdout.write("Number of values: %d\n" % N)
+        sys.stdout.write("Minimum: %.15g\n" % minv)
+        sys.stdout.write("Maximum: %.15g\n" % maxv)
+        sys.stdout.write("Range: %.15g\n" % (maxv - minv))
+        sys.stdout.write("Mean: %.15g\n" % (sum / N))
+        sys.stdout.write(
+            "Arithmetic mean of absolute values: %.15g\n" %
+            (sum3 / N))
+        sys.stdout.write("Variance: %.15g\n" % ((sum2 - sum * sum / N) / N))
+        sys.stdout.write(
+            "Standard deviation: %.15g\n" %
+            (math.sqrt((sum2 - sum * sum / N) / N)))
+        sys.stdout.write(
+            "Coefficient of variation: %.15g\n" %
+            ((math.sqrt((sum2 - sum * sum / N) / N)) /
+             (math.sqrt(sum * sum) / N)))
+        sys.stdout.write("Sum: %.15g\n" % sum)
     else:
     else:
-        sys.stdout.write("n=%d\n"% N)
-        sys.stdout.write("min=%.15g\n"% minv)
-        sys.stdout.write("max=%.15g\n"% maxv)
-        sys.stdout.write("range=%.15g\n"% (maxv - minv))
-        sys.stdout.write("mean=%.15g\n"% (sum/N))
-        sys.stdout.write("mean_abs=%.15g\n"% (sum3/N))
-        sys.stdout.write("variance=%.15g\n"% ((sum2 - sum*sum/N)/N))
-        sys.stdout.write("stddev=%.15g\n"% (math.sqrt((sum2 - sum*sum/N)/N)))
-        sys.stdout.write("coeff_var=%.15g\n"% ((math.sqrt((sum2 - sum*sum/N)/N))/(math.sqrt(sum*sum)/N)))
-        sys.stdout.write("sum=%.15g\n"% sum)
+        sys.stdout.write("n=%d\n" % N)
+        sys.stdout.write("min=%.15g\n" % minv)
+        sys.stdout.write("max=%.15g\n" % maxv)
+        sys.stdout.write("range=%.15g\n" % (maxv - minv))
+        sys.stdout.write("mean=%.15g\n" % (sum / N))
+        sys.stdout.write("mean_abs=%.15g\n" % (sum3 / N))
+        sys.stdout.write("variance=%.15g\n" % ((sum2 - sum * sum / N) / N))
+        sys.stdout.write(
+            "stddev=%.15g\n" %
+            (math.sqrt(
+                (sum2 - sum * sum / N) / N)))
+        sys.stdout.write(
+            "coeff_var=%.15g\n" %
+            ((math.sqrt((sum2 - sum * sum / N) / N)) /
+             (math.sqrt(sum * sum) / N)))
+        sys.stdout.write("sum=%.15g\n" % sum)
 
 
     if not extend:
     if not extend:
         return
         return
@@ -194,27 +210,26 @@ def main():
     # preparations:
     # preparations:
     sortfile(tmp, tmp + ".sort")
     sortfile(tmp, tmp + ".sort")
 
 
-    number = N
     odd = N % 2
     odd = N % 2
-    eostr = ['even','odd'][odd]
+    eostr = ['even', 'odd'][odd]
 
 
     q25pos = round(N * 0.25)
     q25pos = round(N * 0.25)
     if q25pos == 0:
     if q25pos == 0:
-	q25pos = 1
+        q25pos = 1
     q50apos = round(N * 0.50)
     q50apos = round(N * 0.50)
     if q50apos == 0:
     if q50apos == 0:
-	q50apos = 1
+        q50apos = 1
     q50bpos = q50apos + (1 - odd)
     q50bpos = q50apos + (1 - odd)
     q75pos = round(N * 0.75)
     q75pos = round(N * 0.75)
     if q75pos == 0:
     if q75pos == 0:
-	q75pos = 1
+        q75pos = 1
 
 
     ppos = {}
     ppos = {}
     pval = {}
     pval = {}
     for i in range(len(perc)):
     for i in range(len(perc)):
         ppos[i] = round(N * perc[i] / 100)
         ppos[i] = round(N * perc[i] / 100)
-	if ppos[i] == 0:
-	    ppos[i] = 1
+        if ppos[i] == 0:
+            ppos[i] = 1
         pval[i] = 0
         pval[i] = 0
 
 
     inf = file(tmp + ".sort")
     inf = file(tmp + ".sort")
@@ -240,27 +255,45 @@ def main():
         sys.stdout.write("Median (%s N): %.15g\n" % (eostr, q50))
         sys.stdout.write("Median (%s N): %.15g\n" % (eostr, q50))
         sys.stdout.write("3rd Quartile: %.15g\n" % q75)
         sys.stdout.write("3rd Quartile: %.15g\n" % q75)
         for i in range(len(perc)):
         for i in range(len(perc)):
-            if perc[i] == int(perc[i]): # integer
+            if perc[i] == int(perc[i]):  # integer
                 if int(perc[i]) % 10 == 1 and int(perc[i]) != 11:
                 if int(perc[i]) % 10 == 1 and int(perc[i]) != 11:
-                    sys.stdout.write("%dst Percentile: %.15g\n"% (int(perc[i]), pval[i]))
+                    sys.stdout.write(
+                        "%dst Percentile: %.15g\n" %
+                        (int(
+                            perc[i]),
+                            pval[i]))
                 elif int(perc[i]) % 10 == 2 and int(perc[i]) != 12:
                 elif int(perc[i]) % 10 == 2 and int(perc[i]) != 12:
-                    sys.stdout.write("%dnd Percentile: %.15g\n"% (int(perc[i]), pval[i]))
+                    sys.stdout.write(
+                        "%dnd Percentile: %.15g\n" %
+                        (int(
+                            perc[i]),
+                            pval[i]))
                 elif int(perc[i]) % 10 == 3 and int(perc[i]) != 13:
                 elif int(perc[i]) % 10 == 3 and int(perc[i]) != 13:
-                    sys.stdout.write("%drd Percentile: %.15g\n"% (int(perc[i]), pval[i]))
+                    sys.stdout.write(
+                        "%drd Percentile: %.15g\n" %
+                        (int(
+                            perc[i]),
+                            pval[i]))
                 else:
                 else:
-                    sys.stdout.write("%dth Percentile: %.15g\n"% (int(perc[i]), pval[i]))
+                    sys.stdout.write(
+                        "%dth Percentile: %.15g\n" %
+                        (int(
+                            perc[i]),
+                            pval[i]))
             else:
             else:
-                sys.stdout.write("%.15g Percentile: %.15g\n"% (perc[i], pval[i]))
+                sys.stdout.write(
+                    "%.15g Percentile: %.15g\n" %
+                    (perc[i], pval[i]))
     else:
     else:
-        sys.stdout.write("first_quartile=%.15g\n"% q25)
-        sys.stdout.write("median=%.15g\n"% q50)
-        sys.stdout.write("third_quartile=%.15g\n"% q75)
+        sys.stdout.write("first_quartile=%.15g\n" % q25)
+        sys.stdout.write("median=%.15g\n" % q50)
+        sys.stdout.write("third_quartile=%.15g\n" % q75)
         for i in range(len(perc)):
         for i in range(len(perc)):
             percstr = "%.15g" % perc[i]
             percstr = "%.15g" % perc[i]
-            percstr = percstr.replace('.','_')
-            sys.stdout.write("percentile_%s=%.15g\n"% (percstr, pval[i]))
+            percstr = percstr.replace('.', '_')
+            sys.stdout.write("percentile_%s=%.15g\n" % (percstr, pval[i]))
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     atexit.register(cleanup)
     atexit.register(cleanup)
     main()
     main()

+ 34 - 29
scripts/g.extension.all/g.extension.all.py

@@ -6,7 +6,7 @@
 #
 #
 # AUTHOR(S):    Martin Landa <landa.martin gmail.com>
 # AUTHOR(S):    Martin Landa <landa.martin gmail.com>
 #
 #
-# PURPOSE:      Rebuilds or removes locally installed GRASS Addons extensions 
+# PURPOSE:      Rebuilds or removes locally installed GRASS Addons extensions
 #
 #
 # COPYRIGHT:    (C) 2011-2013 by Martin Landa, and the GRASS Development Team
 # COPYRIGHT:    (C) 2011-2013 by Martin Landa, and the GRASS Development Team
 #
 #
@@ -35,23 +35,23 @@
 #% key: f
 #% key: f
 #% label: Force operation (required for removal)
 #% label: Force operation (required for removal)
 #% end
 #% end
-
+from __future__ import print_function
 import os
 import os
 import sys
 import sys
 
 
 try:
 try:
     import xml.etree.ElementTree as etree
     import xml.etree.ElementTree as etree
 except ImportError:
 except ImportError:
-    import elementtree.ElementTree as etree # Python <= 2.4
+    import elementtree.ElementTree as etree  # Python <= 2.4
 
 
-import grass.script as grass
+import grass.script as gscript
 from grass.exceptions import CalledModuleError
 from grass.exceptions import CalledModuleError
 
 
 
 
 def get_extensions():
 def get_extensions():
     addon_base = os.getenv('GRASS_ADDON_BASE')
     addon_base = os.getenv('GRASS_ADDON_BASE')
     if not addon_base:
     if not addon_base:
-        grass.fatal(_("%s not defined") % "GRASS_ADDON_BASE")
+        gscript.fatal(_("%s not defined") % "GRASS_ADDON_BASE")
     fXML = os.path.join(addon_base, 'modules.xml')
     fXML = os.path.join(addon_base, 'modules.xml')
     if not os.path.exists(fXML):
     if not os.path.exists(fXML):
         return []
         return []
@@ -60,51 +60,56 @@ def get_extensions():
     fo = open(fXML, 'r')
     fo = open(fXML, 'r')
     try:
     try:
         tree = etree.fromstring(fo.read())
         tree = etree.fromstring(fo.read())
-    except StandardError as e:
-        grass.error(_("Unable to parse metadata file: %s") % e)
+    except Exception as e:
+        gscript.error(_("Unable to parse metadata file: %s") % e)
         fo.close()
         fo.close()
         return []
         return []
-    
+
     fo.close()
     fo.close()
-    
-    libgis_rev = grass.version()['libgis_revision']
+
+    libgis_rev = gscript.version()['libgis_revision']
     ret = list()
     ret = list()
     for tnode in tree.findall('task'):
     for tnode in tree.findall('task'):
         gnode = tnode.find('libgis')
         gnode = tnode.find('libgis')
         if gnode is not None and \
         if gnode is not None and \
                 gnode.get('revision', '') != libgis_rev:
                 gnode.get('revision', '') != libgis_rev:
             ret.append(tnode.get('name'))
             ret.append(tnode.get('name'))
-    
+
     return ret
     return ret
 
 
+
 def main():
 def main():
     remove = options['operation'] == 'remove'
     remove = options['operation'] == 'remove'
     if remove or flags['f']:
     if remove or flags['f']:
-        extensions = grass.read_command('g.extension',
-                                        quiet = True, flags = 'a').splitlines()
+        extensions = gscript.read_command(
+            'g.extension',
+            quiet=True,
+            flags='a').splitlines()
     else:
     else:
         extensions = get_extensions()
         extensions = get_extensions()
-    
+
     if not extensions:
     if not extensions:
         if remove:
         if remove:
-            grass.info(_("No extension found. Nothing to remove."))
+            gscript.info(_("No extension found. Nothing to remove."))
         else:
         else:
-            grass.info(_("Nothing to rebuild. Rebuilding process can be forced with -f flag."))
+            gscript.info(
+                _("Nothing to rebuild. Rebuilding process can be forced with -f flag."))
         return 0
         return 0
-    
+
     if remove and not flags['f']:
     if remove and not flags['f']:
-        grass.message(_("List of extensions to be removed:"))
-        print os.linesep.join(extensions)
-        grass.message(_("You must use the force flag (-f) to actually remove them. Exiting."))
+        gscript.message(_("List of extensions to be removed:"))
+        print(os.linesep.join(extensions))
+        gscript.message(
+            _("You must use the force flag (-f) to actually remove them. Exiting."))
         return 0
         return 0
-    
+
     for ext in extensions:
     for ext in extensions:
-        grass.message('-' * 60)
+        gscript.message('-' * 60)
         if remove:
         if remove:
-            grass.message(_("Removing extension <%s>...") % ext)
+            gscript.message(_("Removing extension <%s>...") % ext)
         else:
         else:
-            grass.message(_("Reinstalling extension <%s>...") % ext)
-        grass.message('-' * 60)
+            gscript.message(_("Reinstalling extension <%s>...") % ext)
+        gscript.message('-' * 60)
         if remove:
         if remove:
             operation = 'remove'
             operation = 'remove'
             operation_flags = 'f'
             operation_flags = 'f'
@@ -112,13 +117,13 @@ def main():
             operation = 'add'
             operation = 'add'
             operation_flags = ''
             operation_flags = ''
         try:
         try:
-            grass.run_command('g.extension', flags=operation_flags,
-                              extension=ext, operation=operation)
+            gscript.run_command('g.extension', flags=operation_flags,
+                                extension=ext, operation=operation)
         except CalledModuleError:
         except CalledModuleError:
-            grass.error(_("Unable to process extension:%s") % ext)
+            gscript.error(_("Unable to process extension:%s") % ext)
 
 
     return 0
     return 0
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     sys.exit(main())
     sys.exit(main())

+ 17 - 14
scripts/g.extension/g.extension.py

@@ -314,7 +314,7 @@ def get_installed_modules(force=False):
             ))
             ))
         else:
         else:
             ret.append(tnode.get('name').strip())
             ret.append(tnode.get('name').strip())
-    
+
     return ret
     return ret
 
 
 # list extensions (read XML file from grass.osgeo.org/addons)
 # list extensions (read XML file from grass.osgeo.org/addons)
@@ -392,6 +392,7 @@ def get_toolbox_modules(url, name):
 
 
     return tlist
     return tlist
 
 
+
 def get_module_files(mnode):
 def get_module_files(mnode):
     """Return list of module files
     """Return list of module files
 
 
@@ -404,6 +405,7 @@ def get_module_files(mnode):
 
 
     return flist
     return flist
 
 
+
 def get_module_executables(mnode):
 def get_module_executables(mnode):
     """Return list of module executables
     """Return list of module executables
 
 
@@ -412,15 +414,16 @@ def get_module_executables(mnode):
     flist = []
     flist = []
     for filepath in get_module_files(mnode):
     for filepath in get_module_files(mnode):
         if filepath.startswith(options['prefix'] + os.path.sep + 'bin') or \
         if filepath.startswith(options['prefix'] + os.path.sep + 'bin') or \
-           (sys.platform != 'win32' and \
-            filepath.startswith(options['prefix'] + os.path.sep + 'scripts')):
+           (sys.platform != 'win32' and
+                filepath.startswith(options['prefix'] + os.path.sep + 'scripts')):
             filename = os.path.basename(filepath)
             filename = os.path.basename(filepath)
             if sys.platform == 'win32':
             if sys.platform == 'win32':
                 filename = os.path.splitext(filename)[0]
                 filename = os.path.splitext(filename)[0]
             flist.append(filename)
             flist.append(filename)
-    
+
     return flist
     return flist
 
 
+
 def get_optional_params(mnode):
 def get_optional_params(mnode):
     """Return description and keywords as a tuple
     """Return description and keywords as a tuple
 
 
@@ -921,7 +924,7 @@ def install_extension_win(name):
     """Install extension on MS Windows"""
     """Install extension on MS Windows"""
     grass.message(_("Downloading precompiled GRASS Addons <%s>...") %
     grass.message(_("Downloading precompiled GRASS Addons <%s>...") %
                   options['extension'])
                   options['extension'])
-    
+
     # build base URL
     # build base URL
     if build_platform == 'x86_64':
     if build_platform == 'x86_64':
         platform = build_platform
         platform = build_platform
@@ -930,29 +933,29 @@ def install_extension_win(name):
     base_url = "http://wingrass.fsv.cvut.cz/" \
     base_url = "http://wingrass.fsv.cvut.cz/" \
                "grass%(major)s%(minor)s/%(platform)s/addons/" \
                "grass%(major)s%(minor)s/%(platform)s/addons/" \
                "grass-%(major)s.%(minor)s.%(patch)s" % \
                "grass-%(major)s.%(minor)s.%(patch)s" % \
-               {'platform' : platform,
+               {'platform': platform,
                 'major': version[0], 'minor': version[1],
                 'major': version[0], 'minor': version[1],
                 'patch': version[2]}
                 'patch': version[2]}
 
 
     # resolve ZIP URL
     # resolve ZIP URL
     source, url = resolve_source_code(url='{}/{}.zip'.format(base_url, name))
     source, url = resolve_source_code(url='{}/{}.zip'.format(base_url, name))
-    
+
     # to hide non-error messages from subprocesses
     # to hide non-error messages from subprocesses
     if grass.verbosity() <= 2:
     if grass.verbosity() <= 2:
         outdev = open(os.devnull, 'w')
         outdev = open(os.devnull, 'w')
     else:
     else:
         outdev = sys.stdout
         outdev = sys.stdout
-    
+
     # download Addons ZIP file
     # download Addons ZIP file
     os.chdir(TMPDIR)  # this is just to not leave something behind
     os.chdir(TMPDIR)  # this is just to not leave something behind
     srcdir = os.path.join(TMPDIR, name)
     srcdir = os.path.join(TMPDIR, name)
     download_source_code(source=source, url=url, name=name,
     download_source_code(source=source, url=url, name=name,
-                        outdev=outdev, directory=srcdir, tmpdir=TMPDIR)
-    
+                         outdev=outdev, directory=srcdir, tmpdir=TMPDIR)
+
     # copy Addons copy tree to destination directory
     # copy Addons copy tree to destination directory
     move_extracted_files(extract_dir=srcdir, target_dir=options['prefix'],
     move_extracted_files(extract_dir=srcdir, target_dir=options['prefix'],
                          files=os.listdir(srcdir))
                          files=os.listdir(srcdir))
-    
+
     return 0
     return 0
 
 
 
 
@@ -1091,7 +1094,7 @@ def download_source_code(source, url, name, outdev,
         f, h = urlretrieve(url, zip_name)
         f, h = urlretrieve(url, zip_name)
         if h.get('content-type', '') != 'application/zip':
         if h.get('content-type', '') != 'application/zip':
             grass.fatal(_("Extension <%s> not found") % name)
             grass.fatal(_("Extension <%s> not found") % name)
-            
+
         extract_zip(name=zip_name, directory=directory, tmpdir=tmpdir)
         extract_zip(name=zip_name, directory=directory, tmpdir=tmpdir)
         fix_newlines(directory)
         fix_newlines(directory)
     elif source.startswith('remote_') and \
     elif source.startswith('remote_') and \
@@ -1719,9 +1722,9 @@ if __name__ == "__main__":
     global TMPDIR
     global TMPDIR
     TMPDIR = tempfile.mkdtemp()
     TMPDIR = tempfile.mkdtemp()
     atexit.register(cleanup)
     atexit.register(cleanup)
-    
+
     grass_version = grass.version()
     grass_version = grass.version()
     version = grass_version['version'].split('.')
     version = grass_version['version'].split('.')
     build_platform = grass_version['build_platform'].split('-', 1)[0]
     build_platform = grass_version['build_platform'].split('-', 1)[0]
-    
+
     sys.exit(main())
     sys.exit(main())

+ 1 - 1
scripts/g.extension/testsuite/test_addons_modules.py

@@ -99,7 +99,7 @@ class TestModulesFromDifferentSources(TestCase):
         """Test installing extension from local .tar.gz"""
         """Test installing extension from local .tar.gz"""
         self.assertModule('g.extension', extension='r.plus.example',
         self.assertModule('g.extension', extension='r.plus.example',
                           url=os.path.join(self.path,
                           url=os.path.join(self.path,
-                                              'r.plus.example.tar.gz'),
+                                           'r.plus.example.tar.gz'),
                           prefix=self.install_prefix)
                           prefix=self.install_prefix)
         for file in self.files:
         for file in self.files:
             self.assertFileExists(file)
             self.assertFileExists(file)

+ 24 - 20
scripts/g.manual/g.manual.py

@@ -54,6 +54,7 @@ import webbrowser
 from grass.script.utils import basename
 from grass.script.utils import basename
 from grass.script import core as grass
 from grass.script import core as grass
 
 
+
 def start_browser(entry):
 def start_browser(entry):
     if browser and \
     if browser and \
        browser not in ('xdg-open', 'start') and \
        browser not in ('xdg-open', 'start') and \
@@ -61,65 +62,68 @@ def start_browser(entry):
         grass.fatal(_("Browser '%s' not found") % browser)
         grass.fatal(_("Browser '%s' not found") % browser)
 
 
     if flags['o']:
     if flags['o']:
-        major,minor,patch = grass.version()['version'].split('.')
-        url_path = 'http://grass.osgeo.org/grass%s%s/manuals/%s.html' % (major,minor,entry)
+        major, minor, patch = grass.version()['version'].split('.')
+        url_path = 'http://grass.osgeo.org/grass%s%s/manuals/%s.html' % (major, minor, entry)
         if urllib.urlopen(url_path).getcode() != 200:
         if urllib.urlopen(url_path).getcode() != 200:
-            url_path = 'http://grass.osgeo.org/grass%s%s/manuals/addons/%s.html' % (major,minor,entry)
+            url_path = 'http://grass.osgeo.org/grass%s%s/manuals/addons/%s.html' % (
+                major, minor, entry)
     else:
     else:
         path = os.path.join(gisbase, 'docs', 'html', entry + '.html')
         path = os.path.join(gisbase, 'docs', 'html', entry + '.html')
         if not os.path.exists(path) and os.getenv('GRASS_ADDON_BASE'):
         if not os.path.exists(path) and os.getenv('GRASS_ADDON_BASE'):
             path = os.path.join(os.getenv('GRASS_ADDON_BASE'), 'docs', 'html', entry + '.html')
             path = os.path.join(os.getenv('GRASS_ADDON_BASE'), 'docs', 'html', entry + '.html')
-    
+
         if not os.path.exists(path):
         if not os.path.exists(path):
             grass.fatal(_("No HTML manual page entry for '%s'") % entry)
             grass.fatal(_("No HTML manual page entry for '%s'") % entry)
-    
+
         url_path = 'file://' + path
         url_path = 'file://' + path
-    
+
     if browser and browser not in ('xdg-open', 'start'):
     if browser and browser not in ('xdg-open', 'start'):
         webbrowser.register(browser_name, None)
         webbrowser.register(browser_name, None)
-    
+
     grass.verbose(_("Starting browser '%(browser)s' for manual"
     grass.verbose(_("Starting browser '%(browser)s' for manual"
-                    " entry '%(entry)s'...") % \
+                    " entry '%(entry)s'...") %
                   dict(browser=browser_name, entry=entry))
                   dict(browser=browser_name, entry=entry))
-    
+
     try:
     try:
         webbrowser.open(url_path)
         webbrowser.open(url_path)
     except:
     except:
         grass.fatal(_("Error starting browser '%(browser)s' for HTML file"
         grass.fatal(_("Error starting browser '%(browser)s' for HTML file"
                       " '%(path)s'") % dict(browser=browser, path=path))
                       " '%(path)s'") % dict(browser=browser, path=path))
-    
+
+
 def start_man(entry):
 def start_man(entry):
     path = os.path.join(gisbase, 'docs', 'man', 'man1', entry + '.1')
     path = os.path.join(gisbase, 'docs', 'man', 'man1', entry + '.1')
     if not os.path.exists(path) and os.getenv('GRASS_ADDON_BASE'):
     if not os.path.exists(path) and os.getenv('GRASS_ADDON_BASE'):
         path = os.path.join(os.getenv('GRASS_ADDON_BASE'), 'docs', 'man', 'man1', entry + '.1')
         path = os.path.join(os.getenv('GRASS_ADDON_BASE'), 'docs', 'man', 'man1', entry + '.1')
-    
+
     for ext in ['', '.gz', '.bz2']:
     for ext in ['', '.gz', '.bz2']:
         if os.path.exists(path + ext):
         if os.path.exists(path + ext):
             os.execlp('man', 'man', path + ext)
             os.execlp('man', 'man', path + ext)
             grass.fatal(_("Error starting 'man' for '%s'") % path)
             grass.fatal(_("Error starting 'man' for '%s'") % path)
     grass.fatal(_("No manual page entry for '%s'") % entry)
     grass.fatal(_("No manual page entry for '%s'") % entry)
 
 
+
 def main():
 def main():
     global gisbase, browser, browser_name
     global gisbase, browser, browser_name
-    
+
     if flags['i'] and flags['t']:
     if flags['i'] and flags['t']:
         grass.fatal(_("Flags -%c and -%c are mutually exclusive") % ('i', 't'))
         grass.fatal(_("Flags -%c and -%c are mutually exclusive") % ('i', 't'))
-    
+
     special = None
     special = None
     if flags['i']:
     if flags['i']:
         special = 'index'
         special = 'index'
-    elif flags ['t']:
+    elif flags['t']:
         special = 'topics'
         special = 'topics'
-    
+
     if flags['m']:
     if flags['m']:
         start = start_man
         start = start_man
     else:
     else:
         start = start_browser
         start = start_browser
-    
-    entry  = options['entry']
+
+    entry = options['entry']
     gisbase = os.environ['GISBASE']
     gisbase = os.environ['GISBASE']
     browser = os.getenv('GRASS_HTML_BROWSER', '')
     browser = os.getenv('GRASS_HTML_BROWSER', '')
-    
+
     if sys.platform == 'darwin':
     if sys.platform == 'darwin':
         # hack for MacOSX
         # hack for MacOSX
         browser_name = os.getenv('GRASS_HTML_BROWSER_MACOSX', '..').split('.')[2]
         browser_name = os.getenv('GRASS_HTML_BROWSER_MACOSX', '..').split('.')[2]
@@ -128,14 +132,14 @@ def main():
         browser_name = basename(browser, 'exe')
         browser_name = basename(browser, 'exe')
     else:
     else:
         browser_name = basename(browser)
         browser_name = basename(browser)
-    
+
     # keep order!
     # keep order!
     # first test for index...
     # first test for index...
     if special:
     if special:
         start(special)
         start(special)
     else:
     else:
         start(entry)
         start(entry)
-    
+
     return 0
     return 0
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":

+ 25 - 17
scripts/g.search.modules/g.search.modules.py

@@ -50,7 +50,7 @@
 #% description: JSON format
 #% description: JSON format
 #% guisection: Output
 #% guisection: Output
 #%end
 #%end
-
+from __future__ import print_function
 import os
 import os
 import sys
 import sys
 
 
@@ -58,11 +58,12 @@ from grass.script.utils import diff_files, try_rmdir
 from grass.script import core as grass
 from grass.script import core as grass
 
 
 try:
 try:
-    import xml.etree.ElementTree   as etree
+    import xml.etree.ElementTree as etree
 except ImportError:
 except ImportError:
-    import elementtree.ElementTree as etree # Python <= 2.4
+    import elementtree.ElementTree as etree  # Python <= 2.4
+
+COLORIZE = False
 
 
-COLORIZE=False
 
 
 def main():
 def main():
     global COLORIZE
     global COLORIZE
@@ -79,7 +80,8 @@ def main():
 
 
     modules = _search_module(keywords, AND, manpages)
     modules = _search_module(keywords, AND, manpages)
 
 
-    print_results(modules, out_format) 
+    print_results(modules, out_format)
+
 
 
 def print_results(data, out_format=None):
 def print_results(data, out_format=None):
     """
     """
@@ -107,30 +109,34 @@ def print_results(data, out_format=None):
     elif out_format == 'json':
     elif out_format == 'json':
         _print_results_json(data)
         _print_results_json(data)
 
 
+
 def _print_results_shell(data):
 def _print_results_shell(data):
     """Print just the name attribute"""
     """Print just the name attribute"""
 
 
     for item in data:
     for item in data:
-        print item['name']
+        print(item['name'])
+
 
 
 def _print_results_json(data):
 def _print_results_json(data):
     """Print JSON output"""
     """Print JSON output"""
 
 
     import json
     import json
-    print json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))
+    print(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')))
+
 
 
 def _print_results(data):
 def _print_results(data):
 
 
     import textwrap
     import textwrap
 
 
     for item in data:
     for item in data:
-        print '\n{}'.format(colorize(item['name'], attrs=['bold']))
+        print('\n{}'.format(colorize(item['name'], attrs=['bold'])))
         for attr in item['attributes']:
         for attr in item['attributes']:
             out = '{}: {}'.format(attr, item['attributes'][attr])
             out = '{}: {}'.format(attr, item['attributes'][attr])
-            out = textwrap.wrap(out, width=79, initial_indent=4*' ',
-                    subsequent_indent=4*' '+len(attr)*' '+'  ')
+            out = textwrap.wrap(out, width=79, initial_indent=4 * ' ',
+                                subsequent_indent=4 * ' ' + len(attr) * ' ' + '  ')
             for line in out:
             for line in out:
-                print line
+                print(line)
+
 
 
 def colorize(text, attrs=None, pattern=None):
 def colorize(text, attrs=None, pattern=None):
     """Colorize given text input
     """Colorize given text input
@@ -140,7 +146,6 @@ def colorize(text, attrs=None, pattern=None):
     :param string pattern: text to be highlighted in input text
     :param string pattern: text to be highlighted in input text
     :return: colored string
     :return: colored string
     """
     """
-    
 
 
     if COLORIZE:
     if COLORIZE:
         try:
         try:
@@ -156,6 +161,7 @@ def colorize(text, attrs=None, pattern=None):
     else:
     else:
         return colored(text, attrs=attrs)
         return colored(text, attrs=attrs)
 
 
+
 def _search_module(keywords, logical_and=False, manpages=False):
 def _search_module(keywords, logical_and=False, manpages=False):
     """Search modules by given keywords
     """Search modules by given keywords
 
 
@@ -200,11 +206,11 @@ def _search_module(keywords, logical_and=False, manpages=False):
                     found = [True]
                     found = [True]
 
 
                 description = colorize(description,
                 description = colorize(description,
-                                        attrs=['underline'],
-                                        pattern=keyword)
+                                       attrs=['underline'],
+                                       pattern=keyword)
                 module_keywords = colorize(module_keywords,
                 module_keywords = colorize(module_keywords,
-                                            attrs=['underline'],
-                                            pattern=keyword)
+                                           attrs=['underline'],
+                                           pattern=keyword)
 
 
         if False not in found:
         if False not in found:
             found_modules.append({
             found_modules.append({
@@ -217,8 +223,9 @@ def _search_module(keywords, logical_and=False, manpages=False):
 
 
     return found_modules
     return found_modules
 
 
+
 def _basic_search(pattern, name, description, module_keywords):
 def _basic_search(pattern, name, description, module_keywords):
-    
+
     if name.lower().find(pattern) > -1 or\
     if name.lower().find(pattern) > -1 or\
        description.lower().find(pattern) > -1 or\
        description.lower().find(pattern) > -1 or\
        module_keywords.lower().find(pattern) > -1:
        module_keywords.lower().find(pattern) > -1:
@@ -227,6 +234,7 @@ def _basic_search(pattern, name, description, module_keywords):
     else:
     else:
         return False
         return False
 
 
+
 def _manpage_search(pattern, name):
 def _manpage_search(pattern, name):
 
 
     manpage = grass.read_command('g.manual', flags='m', entry=name)
     manpage = grass.read_command('g.manual', flags='m', entry=name)

+ 1 - 1
scripts/g.search.modules/testsuite/test_g_search_modules.py

@@ -52,7 +52,7 @@ class TestSearchModule(TestCase):
         stdout = module.outputs.stdout.split()
         stdout = module.outputs.stdout.split()
         self.assertEqual(stdout[0],
         self.assertEqual(stdout[0],
                          termcolor.colored('r.watershed',
                          termcolor.colored('r.watershed',
-                         attrs=['bold']))
+                                           attrs=['bold']))
 
 
     def test_manual_pages(self):
     def test_manual_pages(self):
         module = SimpleModule('g.search.modules', keyword="kapri", flags="gm")
         module = SimpleModule('g.search.modules', keyword="kapri", flags="gm")

+ 88 - 91
scripts/i.colors.enhance/i.colors.enhance.py

@@ -8,7 +8,7 @@
 #		Hamish Bowman, scripting enhancements
 #		Hamish Bowman, scripting enhancements
 #               Converted to Python by Glynn Clements
 #               Converted to Python by Glynn Clements
 #
 #
-# PURPOSE:      create pretty RGBs: the trick is to remove outliers 
+# PURPOSE:      create pretty RGBs: the trick is to remove outliers
 #               using percentiles (area under the histogram curve)
 #               using percentiles (area under the histogram curve)
 #
 #
 # COPYRIGHT:	(C) 2006, 2008, 2012-2014 by the GRASS Development Team
 # COPYRIGHT:	(C) 2006, 2008, 2012-2014 by the GRASS Development Team
@@ -68,9 +68,9 @@
 #%end
 #%end
 
 
 import sys
 import sys
-import os
-import string
-import grass.script as grass
+
+import grass.script as gscript
+
 try:
 try:
     # new for python 2.6, in 2.5 it may be easy_install'd.
     # new for python 2.6, in 2.5 it may be easy_install'd.
     import multiprocessing as mp
     import multiprocessing as mp
@@ -85,14 +85,16 @@ def get_percentile(map, percentiles):
     val2 = percentiles[1]
     val2 = percentiles[1]
     values = '%s,%s' % (val1, val2)
     values = '%s,%s' % (val1, val2)
 
 
-    s = grass.read_command('r.quantile', input = map, 
-                           percentiles = values, quiet = True)
+    s = gscript.read_command('r.quantile', input=map,
+                             percentiles=values, quiet=True)
 
 
     val_str1 = s.splitlines()[0].split(':')[2]
     val_str1 = s.splitlines()[0].split(':')[2]
     val_str2 = s.splitlines()[1].split(':')[2]
     val_str2 = s.splitlines()[1].split(':')[2]
     return (float(val_str1), float(val_str2))
     return (float(val_str1), float(val_str2))
 
 
 # wrapper to handle multiprocesses communications back to the parent
 # wrapper to handle multiprocesses communications back to the parent
+
+
 def get_percentile_mp(map, percentiles, conn):
 def get_percentile_mp(map, percentiles, conn):
     # Process() doesn't like storing connection parts in
     # Process() doesn't like storing connection parts in
     #  separate dictionaries, only wants to pass through tuples,
     #  separate dictionaries, only wants to pass through tuples,
@@ -101,19 +103,16 @@ def get_percentile_mp(map, percentiles, conn):
     output_pipe, input_pipe = conn
     output_pipe, input_pipe = conn
     input_pipe.close()
     input_pipe.close()
     result = get_percentile(map, percentiles)
     result = get_percentile(map, percentiles)
-    grass.debug('child (%s) (%.1f, %.1f)' % (map, result[0], result[1]))
+    gscript.debug('child (%s) (%.1f, %.1f)' % (map, result[0], result[1]))
     output_pipe.send(result)
     output_pipe.send(result)
     output_pipe.close()
     output_pipe.close()
 
 
+
 def set_colors(map, v0, v1):
 def set_colors(map, v0, v1):
-    rules = [
-	"0% black\n",
-	"%f black\n" % v0,
-	"%f white\n" % v1,
-	"100% white\n"
-	]
-    rules = ''.join(rules)
-    grass.write_command('r.colors', map = map, rules = '-', stdin = rules, quiet = True)
+    rules = ''.join(["0% black\n", "%f black\n" % v0,
+                     "%f white\n" % v1, "100% white\n"])
+    gscript.write_command('r.colors', map=map, rules='-', stdin=rules,
+                          quiet=True)
 
 
 
 
 def main():
 def main():
@@ -124,7 +123,7 @@ def main():
     full = flags['f']
     full = flags['f']
     preserve = flags['p']
     preserve = flags['p']
     reset = flags['r']
     reset = flags['r']
-    
+
     global do_mp
     global do_mp
 
 
     if flags['s']:
     if flags['s']:
@@ -135,92 +134,90 @@ def main():
     # must be more than "2" ?
     # must be more than "2" ?
 
 
     if full:
     if full:
-	for i in [red, green, blue]:
-	    grass.run_command('r.colors', map = i, color = 'grey', quiet = True)
-	sys.exit(0)
+        for i in [red, green, blue]:
+            gscript.run_command('r.colors', map=i, color='grey', quiet=True)
+        sys.exit(0)
 
 
     if reset:
     if reset:
-	for i in [red, green, blue]:
-	    grass.run_command('r.colors', map = i, color = 'grey255', quiet = True)
-	sys.exit(0)
-
+        for i in [red, green, blue]:
+            gscript.run_command('r.colors', map=i, color='grey255', quiet=True)
+        sys.exit(0)
 
 
     if not preserve:
     if not preserve:
         if do_mp:
         if do_mp:
-            grass.message(_("Processing..."))
-	    # set up jobs and launch them
-	    proc = {}
-	    conn = {}
-	    for i in [red, green, blue]:
-	        conn[i] = mp.Pipe()
-	        proc[i] = mp.Process(target = get_percentile_mp,
-				     args = (i, ['2', brightness],
-				     conn[i],))
-		proc[i].start()
-            grass.percent(1, 2, 1)
-            
-	    # collect results and wait for jobs to finish
-	    for i in [red, green, blue]:
-		output_pipe, input_pipe = conn[i]
-		(v0, v1) = input_pipe.recv()
-		grass.debug('parent (%s) (%.1f, %.1f)' % (i, v0, v1))
-		input_pipe.close()
-		proc[i].join()
-		set_colors(i, v0, v1)
-            grass.percent(1, 1, 1)
-	else:
-	    for i in [red, green, blue]:
-	        grass.message(_("Processing..."))
-	        (v0, v1) = get_percentile(i, ['2', brightness])
-	        grass.debug("<%s>:  min=%f   max=%f" % (i, v0, v1))
-	        set_colors(i, v0, v1)
+            gscript.message(_("Processing..."))
+            # set up jobs and launch them
+            proc = {}
+            conn = {}
+            for i in [red, green, blue]:
+                conn[i] = mp.Pipe()
+                proc[i] = mp.Process(target=get_percentile_mp,
+                                     args=(i, ['2', brightness],
+                                           conn[i],))
+                proc[i].start()
+            gscript.percent(1, 2, 1)
+
+            # collect results and wait for jobs to finish
+            for i in [red, green, blue]:
+                output_pipe, input_pipe = conn[i]
+                (v0, v1) = input_pipe.recv()
+                gscript.debug('parent (%s) (%.1f, %.1f)' % (i, v0, v1))
+                input_pipe.close()
+                proc[i].join()
+                set_colors(i, v0, v1)
+            gscript.percent(1, 1, 1)
+        else:
+            for i in [red, green, blue]:
+                gscript.message(_("Processing..."))
+                (v0, v1) = get_percentile(i, ['2', brightness])
+                gscript.debug("<%s>:  min=%f   max=%f" % (i, v0, v1))
+                set_colors(i, v0, v1)
 
 
     else:
     else:
-	all_max = 0
-	all_min = 999999
-
-	if do_mp:
-	    grass.message(_("Processing..."))
-	    # set up jobs and launch jobs
-	    proc = {}
-	    conn = {}
-	    for i in [red, green, blue]:
-		conn[i] = mp.Pipe()
-		proc[i] = mp.Process(target = get_percentile_mp,
-				     args = (i, ['2', brightness],
-				     conn[i],))
-		proc[i].start()
-            grass.percent(1, 2, 1)
-            
-	    # collect results and wait for jobs to finish
-	    for i in [red, green, blue]:
-		output_pipe, input_pipe = conn[i]
-		(v0, v1) = input_pipe.recv()
-		grass.debug('parent (%s) (%.1f, %.1f)' % (i, v0, v1))
-		input_pipe.close()
-		proc[i].join()
-		all_min = min(all_min, v0)
-		all_max = max(all_max, v1)
-            grass.percent(1, 1, 1)
-	else:
-	    for i in [red, green, blue]:
-		grass.message(_("Processing..."))
-		(v0, v1) = get_percentile(i, ['2', brightness])
-		grass.debug("<%s>:  min=%f   max=%f" % (i, v0, v1))
-		all_min = min(all_min, v0)
-		all_max = max(all_max, v1)
-
-	grass.debug("all_min=%f   all_max=%f" % (all_min, all_max))
-	for i in [red, green, blue]:
-	    set_colors(i, all_min, all_max)
+        all_max = 0
+        all_min = 999999
 
 
+        if do_mp:
+            gscript.message(_("Processing..."))
+            # set up jobs and launch jobs
+            proc = {}
+            conn = {}
+            for i in [red, green, blue]:
+                conn[i] = mp.Pipe()
+                proc[i] = mp.Process(target=get_percentile_mp,
+                                     args=(i, ['2', brightness],
+                                           conn[i],))
+                proc[i].start()
+            gscript.percent(1, 2, 1)
+
+            # collect results and wait for jobs to finish
+            for i in [red, green, blue]:
+                output_pipe, input_pipe = conn[i]
+                (v0, v1) = input_pipe.recv()
+                gscript.debug('parent (%s) (%.1f, %.1f)' % (i, v0, v1))
+                input_pipe.close()
+                proc[i].join()
+                all_min = min(all_min, v0)
+                all_max = max(all_max, v1)
+            gscript.percent(1, 1, 1)
+        else:
+            for i in [red, green, blue]:
+                gscript.message(_("Processing..."))
+                (v0, v1) = get_percentile(i, ['2', brightness])
+                gscript.debug("<%s>:  min=%f   max=%f" % (i, v0, v1))
+                all_min = min(all_min, v0)
+                all_max = max(all_max, v1)
+
+        gscript.debug("all_min=%f   all_max=%f" % (all_min, all_max))
+        for i in [red, green, blue]:
+            set_colors(i, all_min, all_max)
 
 
     # write cmd history:
     # write cmd history:
-    mapset = grass.gisenv()['MAPSET']
+    mapset = gscript.gisenv()['MAPSET']
     for i in [red, green, blue]:
     for i in [red, green, blue]:
-        if grass.find_file(i)['mapset'] == mapset:
-            grass.raster_history(i)
+        if gscript.find_file(i)['mapset'] == mapset:
+            gscript.raster_history(i)
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     main()
     main()

+ 33 - 30
scripts/i.image.mosaic/i.image.mosaic.py

@@ -32,67 +32,70 @@
 #%end
 #%end
 #%option G_OPT_R_OUTPUT
 #%option G_OPT_R_OUTPUT
 #%end
 #%end
+from __future__ import print_function
+
+import grass.script as gscript
 
 
-import sys
-import os
-import grass.script as grass
 
 
 def copy_colors(fh, map, offset):
 def copy_colors(fh, map, offset):
-    p = grass.pipe_command('r.colors.out', map = map)
+    p = gscript.pipe_command('r.colors.out', map=map)
     for line in p.stdout:
     for line in p.stdout:
-	f = line.rstrip('\r\n').split(' ')
-	if offset:
-	    if f[0] in ['nv', 'default']:
-		continue
-	    f[0] = str(float(f[0]) + offset)
-	fh.write(' '.join(f) + '\n')
+        f = line.rstrip('\r\n').split(' ')
+        if offset:
+            if f[0] in ['nv', 'default']:
+                continue
+            f[0] = str(float(f[0]) + offset)
+        fh.write(' '.join(f) + '\n')
     p.wait()
     p.wait()
 
 
+
 def get_limit(map):
 def get_limit(map):
-    return grass.raster_info(map)['max']
+    return gscript.raster_info(map)['max']
+
 
 
 def make_expression(i, count):
 def make_expression(i, count):
     if i > count:
     if i > count:
-	return "null()"
+        return "null()"
     else:
     else:
-	e = make_expression(i + 1, count)
-	return "if(isnull($image%d),%s,$image%d+$offset%d)" % (i, e, i, i)
+        e = make_expression(i + 1, count)
+        return "if(isnull($image%d),%s,$image%d+$offset%d)" % (i, e, i, i)
+
 
 
 def main():
 def main():
     images = options['input'].split(',')
     images = options['input'].split(',')
     output = options['output']
     output = options['output']
 
 
     count = len(images)
     count = len(images)
-
-    grass.warning(_('Do not forget to set region properly to cover all images.'))
+    msg = _('Do not forget to set region properly to cover all images.')
+    gscript.warning(msg)
 
 
     offset = 0
     offset = 0
     offsets = []
     offsets = []
     parms = {}
     parms = {}
     for n, img in enumerate(images):
     for n, img in enumerate(images):
-	offsets.append(offset)
-	parms['image%d' % (n + 1)] = img
-	parms['offset%d' % (n + 1)] = offset
-	offset += get_limit(img) + 1
+        offsets.append(offset)
+        parms['image%d' % (n + 1)] = img
+        parms['offset%d' % (n + 1)] = offset
+        offset += get_limit(img) + 1
 
 
-    grass.message(_("Mosaicing %d images...") % count)
+    gscript.message(_("Mosaicing %d images...") % count)
 
 
-    grass.mapcalc("$output = " + make_expression(1, count),
-		  output = output, **parms)
+    gscript.mapcalc("$output = " + make_expression(1, count),
+                    output=output, **parms)
 
 
-    #modify the color table:
-    p = grass.feed_command('r.colors', map = output, rules='-')
+    # modify the color table:
+    p = gscript.feed_command('r.colors', map=output, rules='-')
     for img, offset in zip(images, offsets):
     for img, offset in zip(images, offsets):
-	print img, offset
-	copy_colors(p.stdin, img, offset)
+        print(img, offset)
+        copy_colors(p.stdin, img, offset)
     p.stdin.close()
     p.stdin.close()
     p.wait()
     p.wait()
 
 
-    grass.message(_("Done. Raster map <%s> created.") % output)
+    gscript.message(_("Done. Raster map <%s> created.") % output)
 
 
     # write cmd history:
     # write cmd history:
-    grass.raster_history(output)
+    gscript.raster_history(output)
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     main()
     main()

+ 114 - 106
scripts/i.in.spotvgt/i.in.spotvgt.py

@@ -23,7 +23,7 @@
 #      -  gdal: http://www.gdal.org
 #      -  gdal: http://www.gdal.org
 #
 #
 # Notes:
 # Notes:
-# * According to the faq (http://www.vgt.vito.be/faq/faq.html), SPOT vegetation 
+# * According to the faq (http://www.vgt.vito.be/faq/faq.html), SPOT vegetation
 #   coordinates refer to the center of a pixel.
 #   coordinates refer to the center of a pixel.
 # * GDAL coordinates refer to the corner of a pixel
 # * GDAL coordinates refer to the corner of a pixel
 #   -> correction of 0001/0001_LOG.TXT coordinates by 0.5 pixel
 #   -> correction of 0001/0001_LOG.TXT coordinates by 0.5 pixel
@@ -48,7 +48,7 @@
 import os
 import os
 import atexit
 import atexit
 import string
 import string
-import grass.script as grass
+import grass.script as gscript
 from grass.exceptions import CalledModuleError
 from grass.exceptions import CalledModuleError
 
 
 
 
@@ -67,103 +67,109 @@ vrt = """<VRTDataset rasterXSize="$XSIZE" rasterYSize="$YSIZE">
  </VRTRasterBand>
  </VRTRasterBand>
 </VRTDataset>"""
 </VRTDataset>"""
 
 
-#### a function for writing VRT files
+# a function for writing VRT files
+
+
 def create_VRT_file(projfile, vrtfile, infile):
 def create_VRT_file(projfile, vrtfile, infile):
     fh = file(projfile)
     fh = file(projfile)
     kv = {}
     kv = {}
     for l in fh:
     for l in fh:
-	f = l.rstrip('\r\n').split()
-	if f < 2:
-	    continue
-	kv[f[0]] = f[1]
+        f = l.rstrip('\r\n').split()
+        if f < 2:
+            continue
+        kv[f[0]] = f[1]
     fh.close()
     fh.close()
 
 
     north_center = kv['CARTO_UPPER_LEFT_Y']
     north_center = kv['CARTO_UPPER_LEFT_Y']
-    south_center = kv['CARTO_LOWER_LEFT_Y']
-    east_center  = kv['CARTO_UPPER_RIGHT_X']
-    west_center  = kv['CARTO_UPPER_LEFT_X']
+    # south_center = kv['CARTO_LOWER_LEFT_Y']
+    # east_center = kv['CARTO_UPPER_RIGHT_X']
+    west_center = kv['CARTO_UPPER_LEFT_X']
     map_proj_res = kv['MAP_PROJ_RESOLUTION']
     map_proj_res = kv['MAP_PROJ_RESOLUTION']
-    xsize        = kv['IMAGE_UPPER_RIGHT_COL']
-    ysize        = kv['IMAGE_LOWER_RIGHT_ROW']
+    xsize = kv['IMAGE_UPPER_RIGHT_COL']
+    ysize = kv['IMAGE_LOWER_RIGHT_ROW']
 
 
-    resolution   = float(map_proj_res)
+    resolution = float(map_proj_res)
     north_corner = float(north_center) + resolution / 2
     north_corner = float(north_center) + resolution / 2
-    south_corner = float(south_center) - resolution / 2
-    east_corner  = float(east_center ) + resolution / 2
-    west_corner  = float(west_center ) - resolution / 2
+    # south_corner = float(south_center) - resolution / 2
+    # east_corner = float(east_center) + resolution / 2
+    west_corner = float(west_center) - resolution / 2
 
 
     t = string.Template(vrt)
     t = string.Template(vrt)
-    s = t.substitute(NORTHCORNER = north_corner, WESTCORNER = west_corner,
-		     XSIZE = xsize, YSIZE = ysize, RESOLUTION = map_proj_res,
-		     FILENAME = infile)
+    s = t.substitute(NORTHCORNER=north_corner, WESTCORNER=west_corner,
+                     XSIZE=xsize, YSIZE=ysize, RESOLUTION=map_proj_res,
+                     FILENAME=infile)
     outf = file(vrtfile, 'w')
     outf = file(vrtfile, 'w')
     outf.write(s)
     outf.write(s)
     outf.close()
     outf.close()
 
 
+
 def cleanup():
 def cleanup():
-   #### clean up the mess
-   grass.try_remove(vrtfile)
-   grass.try_remove(tmpfile)
+    # clean up the mess
+    gscript.try_remove(vrtfile)
+    gscript.try_remove(tmpfile)
+
 
 
 def main():
 def main():
     global vrtfile, tmpfile
     global vrtfile, tmpfile
 
 
-    infile  = options['input']
+    infile = options['input']
     rast = options['output']
     rast = options['output']
     also = flags['a']
     also = flags['a']
 
 
-    #### check for gdalinfo (just to check if installation is complete)
-    if not grass.find_program('gdalinfo', '--help'):
-	grass.fatal(_("'gdalinfo' not found, install GDAL tools first (http://www.gdal.org)"))
+    # check for gdalinfo (just to check if installation is complete)
+    if not gscript.find_program('gdalinfo', '--help'):
+        gscript.fatal(_("'gdalinfo' not found, install GDAL tools first "
+                        "(http://www.gdal.org)"))
 
 
     pid = str(os.getpid())
     pid = str(os.getpid())
-    tmpfile = grass.tempfile()
+    tmpfile = gscript.tempfile()
 
 
-    ################### let's go
+    # let's go
 
 
     spotdir = os.path.dirname(infile)
     spotdir = os.path.dirname(infile)
-    spotname = grass.basename(infile, 'hdf')
+    spotname = gscript.basename(infile, 'hdf')
 
 
     if rast:
     if rast:
-	name = rast
+        name = rast
     else:
     else:
-	name = spotname
+        name = spotname
 
 
-    if not grass.overwrite() and grass.find_file(name)['file']:
-	grass.fatal(_("<%s> already exists. Aborting.") % name)
+    if not gscript.overwrite() and gscript.find_file(name)['file']:
+        gscript.fatal(_("<%s> already exists. Aborting.") % name)
 
 
-    # still a ZIP file?  (is this portable?? see the r.in.srtm script for ideas)
+    # still a ZIP file?  (is this portable?? see the r.in.srtm script for
+    # ideas)
     if infile.lower().endswith('.zip'):
     if infile.lower().endswith('.zip'):
-	grass.fatal(_("Please extract %s before import.") % infile)
+        gscript.fatal(_("Please extract %s before import.") % infile)
 
 
     try:
     try:
-	p = grass.Popen(['file', '-ib', infile], stdout = grass.PIPE)
-	s = p.communicate()[0]
-	if s == "application/x-zip":
-	    grass.fatal(_("Please extract %s before import.") % infile)
+        p = gscript.Popen(['file', '-ib', infile], stdout=gscript.PIPE)
+        s = p.communicate()[0]
+        if s == "application/x-zip":
+            gscript.fatal(_("Please extract %s before import.") % infile)
     except:
     except:
-	pass
+        pass
 
 
-    ### create VRT header for NDVI
+    # create VRT header for NDVI
 
 
     projfile = os.path.join(spotdir, "0001_LOG.TXT")
     projfile = os.path.join(spotdir, "0001_LOG.TXT")
     vrtfile = tmpfile + '.vrt'
     vrtfile = tmpfile + '.vrt'
 
 
     # first process the NDVI:
     # first process the NDVI:
-    grass.try_remove(vrtfile)
+    gscript.try_remove(vrtfile)
     create_VRT_file(projfile, vrtfile, infile)
     create_VRT_file(projfile, vrtfile, infile)
 
 
-    ## let's import the NDVI map...
-    grass.message(_("Importing SPOT VGT NDVI map..."))
+    # let's import the NDVI map...
+    gscript.message(_("Importing SPOT VGT NDVI map..."))
     try:
     try:
-        grass.run_command('r.in.gdal', input=vrtfile, output=name)
+        gscript.run_command('r.in.gdal', input=vrtfile, output=name)
     except CalledModuleError:
     except CalledModuleError:
-        grass.fatal(_("An error occurred. Stop."))
+        gscript.fatal(_("An error occurred. Stop."))
 
 
-    grass.message(_("Imported SPOT VEGETATION NDVI map <%s>.") % name)
+    gscript.message(_("Imported SPOT VEGETATION NDVI map <%s>.") % name)
 
 
     #################
     #################
-    ## http://www.vgt.vito.be/faq/FAQS/faq19.html
+    # http://www.vgt.vito.be/faq/FAQS/faq19.html
     # What is the relation between the digital number and the real NDVI ?
     # What is the relation between the digital number and the real NDVI ?
     # Real NDVI =coefficient a * Digital Number + coefficient b
     # Real NDVI =coefficient a * Digital Number + coefficient b
     #           = a * DN +b
     #           = a * DN +b
@@ -173,28 +179,29 @@ def main():
 
 
     # clone current region
     # clone current region
     # switch to a temporary region
     # switch to a temporary region
-    grass.use_temp_region()
+    gscript.use_temp_region()
 
 
-    grass.run_command('g.region', raster = name, quiet = True)
+    gscript.run_command('g.region', raster=name, quiet=True)
 
 
-    grass.message(_("Remapping digital numbers to NDVI..."))
+    gscript.message(_("Remapping digital numbers to NDVI..."))
     tmpname = "%s_%s" % (name, pid)
     tmpname = "%s_%s" % (name, pid)
-    grass.mapcalc("$tmpname = 0.004 * $name - 0.1", tmpname = tmpname, name = name)
-    grass.run_command('g.remove', type = 'raster', name = name, quiet = True, flags = 'f')
-    grass.run_command('g.rename', raster = (tmpname, name), quiet = True)
+    gscript.mapcalc("$tmpname = 0.004 * $name - 0.1", tmpname=tmpname, name=name)
+    gscript.run_command('g.remove', type='raster', name=name, quiet=True,
+                        flags='f')
+    gscript.run_command('g.rename', raster=(tmpname, name), quiet=True)
 
 
     # write cmd history:
     # write cmd history:
-    grass.raster_history(name)
+    gscript.raster_history(name)
 
 
-    #apply color table:
-    grass.run_command('r.colors', map = name, color = 'ndvi', quiet = True)
+    # apply color table:
+    gscript.run_command('r.colors', map=name, color='ndvi', quiet=True)
 
 
     ##########################
     ##########################
     # second, optionally process the SM quality map:
     # second, optionally process the SM quality map:
-    
-    #SM Status Map
+
+    # SM Status Map
     # http://nieuw.vgt.vito.be/faq/FAQS/faq22.html
     # http://nieuw.vgt.vito.be/faq/FAQS/faq22.html
-    #Data about
+    # Data about
     # Bit NR 7: Radiometric quality for B0 coded as 0 if bad and 1 if good
     # Bit NR 7: Radiometric quality for B0 coded as 0 if bad and 1 if good
     # Bit NR 6: Radiometric quality for B2 coded as 0 if bad and 1 if good
     # Bit NR 6: Radiometric quality for B2 coded as 0 if bad and 1 if good
     # Bit NR 5: Radiometric quality for B3 coded as 0 if bad and 1 if good
     # Bit NR 5: Radiometric quality for B3 coded as 0 if bad and 1 if good
@@ -205,7 +212,7 @@ def main():
     # Bit NR 0:	0	1	0		1
     # Bit NR 0:	0	1	0		1
     # 		clear	shadow	uncertain	cloud
     # 		clear	shadow	uncertain	cloud
     #
     #
-    #Note:
+    # Note:
     # pos 7     6    5    4    3    2   1   0 (bit position)
     # pos 7     6    5    4    3    2   1   0 (bit position)
     #   128    64   32   16    8    4   2   1 (values for 8 bit)
     #   128    64   32   16    8    4   2   1 (values for 8 bit)
     #
     #
@@ -218,54 +225,55 @@ def main():
     # A good map threshold: >= 248
     # A good map threshold: >= 248
 
 
     if also:
     if also:
-	grass.message(_("Importing SPOT VGT NDVI quality map..."))
-	grass.try_remove(vrtfile)
-	qname = spotname.replace('NDV','SM')
-	qfile = os.path.join(spotdir, qname)
-	create_VRT_file(projfile, vrtfile, qfile)
-
-	## let's import the SM quality map...
-	smfile = name + '.sm'
+        gscript.message(_("Importing SPOT VGT NDVI quality map..."))
+        gscript.try_remove(vrtfile)
+        qname = spotname.replace('NDV', 'SM')
+        qfile = os.path.join(spotdir, qname)
+        create_VRT_file(projfile, vrtfile, qfile)
+
+        # let's import the SM quality map...
+        smfile = name + '.sm'
         try:
         try:
-            grass.run_command('r.in.gdal', input=vrtfile, output=smfile)
+            gscript.run_command('r.in.gdal', input=vrtfile, output=smfile)
         except CalledModuleError:
         except CalledModuleError:
-            grass.fatal(_("An error occurred. Stop."))
-
-	# some of the possible values:
-	rules = [r + '\n' for r in [
-	    '8 50 50 50',
-	    '11 70 70 70',
-	    '12 90 90 90',
-	    '60 grey',
-	    '155 blue',
-	    '232 violet',
-	    '235 red',
-	    '236 brown',
-	    '248 orange',
-	    '251 yellow',
-	    '252 green'
-	    ]]
-	grass.write_command('r.colors', map = smfile, rules = '-', stdin = rules)
-
-	grass.message(_("Imported SPOT VEGETATION SM quality map <%s>.") % smfile)
-	grass.message(_("Note: A snow map can be extracted by category 252 (d.rast %s cat=252)") % smfile)
-	grass.message("")
-	grass.message(_("Filtering NDVI map by Status Map quality layer..."))
-
-	filtfile = "%s_filt" % name
-	grass.mapcalc("$filtfile = if($smfile % 4 == 3 || ($smfile / 16) % 16 == 0, null(), $name)",
-		      filtfile = filtfile, smfile = smfile, name = name)
-	grass.run_command('r.colors', map = filtfile, color = 'ndvi', quiet = True)
-	grass.message(_("Filtered SPOT VEGETATION NDVI map <%s>.") % filtfile)
-
-	# write cmd history:
-	grass.raster_history(smfile)
-	grass.raster_history(filtfile)
-
-    grass.message(_("Done."))
+            gscript.fatal(_("An error occurred. Stop."))
+
+        # some of the possible values:
+        rules = [r + '\n' for r in ['8 50 50 50',
+                                    '11 70 70 70',
+                                    '12 90 90 90',
+                                    '60 grey',
+                                    '155 blue',
+                                    '232 violet',
+                                    '235 red',
+                                    '236 brown',
+                                    '248 orange',
+                                    '251 yellow',
+                                    '252 green']]
+        gscript.write_command('r.colors', map=smfile, rules='-', stdin=rules)
+
+        gscript.message(_("Imported SPOT VEGETATION SM quality map <%s>.") %
+                        smfile)
+        gscript.message(_("Note: A snow map can be extracted by category "
+                          "252 (d.rast %s cat=252)") % smfile)
+        gscript.message("")
+        gscript.message(_("Filtering NDVI map by Status Map quality layer..."))
+
+        filtfile = "%s_filt" % name
+        gscript.mapcalc("$filtfile = if($smfile % 4 == 3 || "
+                        "($smfile / 16) % 16 == 0, null(), $name)",
+                        filtfile=filtfile, smfile=smfile, name=name)
+        gscript.run_command('r.colors', map=filtfile, color='ndvi', quiet=True)
+        gscript.message(_("Filtered SPOT VEGETATION NDVI map <%s>.") %
+                        filtfile)
+
+        # write cmd history:
+        gscript.raster_history(smfile)
+        gscript.raster_history(filtfile)
+
+    gscript.message(_("Done."))
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     atexit.register(cleanup)
     atexit.register(cleanup)
     main()
     main()
-

+ 1 - 2
scripts/i.oif/i.oif.py

@@ -121,7 +121,6 @@ def main():
             kv = parse_key_val(pout[band])
             kv = parse_key_val(pout[band])
             stddev[band] = float(kv['stddev'])
             stddev[band] = float(kv['stddev'])
 
 
-
     grass.message(_("Calculating Correlation Matrix..."))
     grass.message(_("Calculating Correlation Matrix..."))
     correlation = {}
     correlation = {}
     s = grass.read_command('r.covar', flags='r', map=[band for band in bands],
     s = grass.read_command('r.covar', flags='r', map=[band for band in bands],
@@ -141,7 +140,7 @@ def main():
         oif.append((oifcalc(stddev, correlation, *p), p))
         oif.append((oifcalc(stddev, correlation, *p), p))
     oif.sort(reverse=True)
     oif.sort(reverse=True)
 
 
-    grass.verbose(_("The Optimum Index Factor analysis result " \
+    grass.verbose(_("The Optimum Index Factor analysis result "
                     "(best combination shown first):"))
                     "(best combination shown first):"))
 
 
     if shell:
     if shell:

+ 25 - 23
scripts/i.spectral/i.spectral.py

@@ -20,7 +20,7 @@
 #
 #
 # written by Markus Neteler 18. August 1998
 # written by Markus Neteler 18. August 1998
 #            neteler geog.uni-hannover.de
 #            neteler geog.uni-hannover.de
-# 
+#
 # bugfix: 25. Nov.98/20. Jan. 1999
 # bugfix: 25. Nov.98/20. Jan. 1999
 # 3 March 2006: Added multiple images and group support by Francesco Pirotti - CIRGEO
 # 3 March 2006: Added multiple images and group support by Francesco Pirotti - CIRGEO
 #
 #
@@ -77,20 +77,22 @@
 import os
 import os
 import atexit
 import atexit
 from grass.script.utils import try_rmdir
 from grass.script.utils import try_rmdir
-from grass.script import core as grass
+from grass.script import core as gcore
 
 
 
 
 def cleanup():
 def cleanup():
     try_rmdir(tmp_dir)
     try_rmdir(tmp_dir)
 
 
+
 def write2textf(what, output):
 def write2textf(what, output):
     outf = open(output, 'w')
     outf = open(output, 'w')
-    i=0
+    i = 0
     for row in enumerate(what):
     for row in enumerate(what):
-        i=i+1
-        outf.write("%d, %s\n" % (i,row))
+        i = i + 1
+        outf.write("%d, %s\n" % (i, row))
     outf.close()
     outf.close()
 
 
+
 def draw_gnuplot(what, xlabels, output, img_format, coord_legend):
 def draw_gnuplot(what, xlabels, output, img_format, coord_legend):
     xrange = 0
     xrange = 0
 
 
@@ -107,12 +109,12 @@ def draw_gnuplot(what, xlabels, output, img_format, coord_legend):
     if output:
     if output:
         if img_format == 'png':
         if img_format == 'png':
             term_opts = "png truecolor large size 825,550"
             term_opts = "png truecolor large size 825,550"
-	elif img_format == 'eps':
+        elif img_format == 'eps':
             term_opts = "postscript eps color solid size 6,4"
             term_opts = "postscript eps color solid size 6,4"
-	elif img_format == 'svg':
+        elif img_format == 'svg':
             term_opts = "svg size 825,550 dynamic solid"
             term_opts = "svg size 825,550 dynamic solid"
         else:
         else:
-            grass.fatal(_("Programmer error (%s)") % img_format)
+            gcore.fatal(_("Programmer error (%s)") % img_format)
 
 
         lines += [
         lines += [
             "set term " + term_opts,
             "set term " + term_opts,
@@ -152,9 +154,9 @@ def draw_gnuplot(what, xlabels, output, img_format, coord_legend):
     plotf.close()
     plotf.close()
 
 
     if output:
     if output:
-        grass.call(['gnuplot', plotfile])
+        gcore.call(['gnuplot', plotfile])
     else:
     else:
-        grass.call(['gnuplot', '-persist', plotfile])
+        gcore.call(['gnuplot', '-persist', plotfile])
 
 
 
 
 def draw_linegraph(what):
 def draw_linegraph(what):
@@ -175,7 +177,7 @@ def draw_linegraph(what):
         yf.close()
         yf.close()
         yfiles.append(yfile)
         yfiles.append(yfile)
 
 
-    sienna = '#%02x%02x%02x' % (160,  82, 45)
+    sienna = '#%02x%02x%02x' % (160, 82, 45)
     coral = '#%02x%02x%02x' % (255, 127, 80)
     coral = '#%02x%02x%02x' % (255, 127, 80)
     gp_colors = ['red', 'green', 'blue', 'magenta', 'cyan', sienna, 'orange',
     gp_colors = ['red', 'green', 'blue', 'magenta', 'cyan', sienna, 'orange',
                  coral]
                  coral]
@@ -185,7 +187,7 @@ def draw_linegraph(what):
         colors += gp_colors
         colors += gp_colors
     colors = colors[0:len(what)]
     colors = colors[0:len(what)]
 
 
-    grass.run_command('d.linegraph', x_file=xfile, y_file=yfiles,
+    gcore.run_command('d.linegraph', x_file=xfile, y_file=yfiles,
                       y_color=colors, title='Spectral signatures',
                       y_color=colors, title='Spectral signatures',
                       x_title='Bands', y_title='DN Value')
                       x_title='Bands', y_title='DN Value')
 
 
@@ -201,26 +203,26 @@ def main():
     textfile = flags['t']
     textfile = flags['t']
 
 
     global tmp_dir
     global tmp_dir
-    tmp_dir = grass.tempdir()
-    
+    tmp_dir = gcore.tempdir()
+
     if not group and not raster:
     if not group and not raster:
-        grass.fatal(_("Either group= or raster= is required"))
+        gcore.fatal(_("Either group= or raster= is required"))
 
 
     if group and raster:
     if group and raster:
-        grass.fatal(_("group= and raster= are mutually exclusive"))
+        gcore.fatal(_("group= and raster= are mutually exclusive"))
 
 
     # -t needs an output filename
     # -t needs an output filename
     if textfile and not output:
     if textfile and not output:
-        grass.fatal(_("Writing to text file requires output=filename"))
+        gcore.fatal(_("Writing to text file requires output=filename"))
 
 
     # check if gnuplot is present
     # check if gnuplot is present
-    if gnuplot and not grass.find_program('gnuplot', '-V'):
-        grass.fatal(_("gnuplot required, please install first"))
+    if gnuplot and not gcore.find_program('gnuplot', '-V'):
+        gcore.fatal(_("gnuplot required, please install first"))
 
 
     # get data from group listing and set the x-axis labels
     # get data from group listing and set the x-axis labels
     if group:
     if group:
         # Parse the group list output
         # Parse the group list output
-        s = grass.read_command('i.group', flags='g', group=group, quiet=True)
+        s = gcore.read_command('i.group', flags='g', group=group, quiet=True)
         rastermaps = s.splitlines()
         rastermaps = s.splitlines()
     else:
     else:
         # get data from list of files and set the x-axis labels
         # get data from list of files and set the x-axis labels
@@ -231,10 +233,10 @@ def main():
 
 
     # get y-data for gnuplot-data file
     # get y-data for gnuplot-data file
     what = []
     what = []
-    s = grass.read_command('r.what', map=rastermaps, coordinates=coords,
+    s = gcore.read_command('r.what', map=rastermaps, coordinates=coords,
                            null='0', quiet=True)
                            null='0', quiet=True)
     if len(s) == 0:
     if len(s) == 0:
-        grass.fatal(_('No data returned from query'))
+        gcore.fatal(_('No data returned from query'))
 
 
     for l in s.splitlines():
     for l in s.splitlines():
         f = l.split('|')
         f = l.split('|')
@@ -254,6 +256,6 @@ def main():
         draw_linegraph(what)
         draw_linegraph(what)
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gcore.parser()
     atexit.register(cleanup)
     atexit.register(cleanup)
     main()
     main()

+ 20 - 20
scripts/i.tasscap/i.tasscap.py

@@ -75,24 +75,24 @@ import grass.script as grass
 
 
 # weights for 6 Landsat bands: TM4, TM5, TM7, OLI
 # weights for 6 Landsat bands: TM4, TM5, TM7, OLI
 # MODIS: Red, NIR1, Blue, Green, NIR2, SWIR1, SWIR2
 # MODIS: Red, NIR1, Blue, Green, NIR2, SWIR1, SWIR2
-parms = [[(0.3037,  0.2793,  0.4743,  0.5585,  0.5082,  0.1863),  # Landsat TM4
-         (-0.2848, -0.2435, -0.5435,  0.7243,  0.0840, -0.1800),
-          (0.1509,  0.1973,  0.3279,  0.3406, -0.7112, -0.4572)],
-         [(0.2909,  0.2493,  0.4806,  0.5568,  0.4438,  0.1706, 10.3695),  # Landsat TM5
-         (-0.2728, -0.2174, -0.5508,  0.7221,  0.0733, -0.1648, -0.7310),
-          (0.1446,  0.1761,  0.3322,  0.3396, -0.6210, -0.4186, -3.3828),
-          (0.8461, -0.0731, -0.4640, -0.0032, -0.0492, -0.0119,  0.7879)],
-         [(0.3561,  0.3972,  0.3904,  0.6966,  0.2286,  0.1596),  # Landsat TM7
-         (-0.3344, -0.3544, -0.4556,  0.6966, -0.0242, -0.2630),
-          (0.2626,  0.2141,  0.0926,  0.0656, -0.7629, -0.5388),
-          (0.0805, -0.0498,  0.1950, -0.1327,  0.5752, -0.7775)],
-         [(0.3029,  0.2786,  0.4733,  0.5599,  0.5080,  0.1872),  # Landsat OLI
-         (-0.2941, -0.2430, -0.5424,  0.7276,  0.0713, -0.1608),
-          (0.1511,  0.1973,  0.3283,  0.3407, -0.7117, -0.4559),
-         (-0.8239,  0.0849,  0.4396, -0.0580,  0.2013, -0.2773)],
-         [(0.4395,  0.5945,  0.2460,  0.3918,  0.3506,  0.2136,  0.2678),  # MODIS
-         (-0.4064,  0.5129, -0.2744, -0.2893,  0.4882, -0.0036, -0.4169),
-          (0.1147,  0.2489,  0.2408,  0.3132, -0.3122, -0.6416, -0.5087)]]
+parms = [[(0.3037, 0.2793, 0.4743, 0.5585, 0.5082, 0.1863),  # Landsat TM4
+          (-0.2848, -0.2435, -0.5435, 0.7243, 0.0840, -0.1800),
+          (0.1509, 0.1973, 0.3279, 0.3406, -0.7112, -0.4572)],
+         [(0.2909, 0.2493, 0.4806, 0.5568, 0.4438, 0.1706, 10.3695),  # Landsat TM5
+          (-0.2728, -0.2174, -0.5508, 0.7221, 0.0733, -0.1648, -0.7310),
+          (0.1446, 0.1761, 0.3322, 0.3396, -0.6210, -0.4186, -3.3828),
+          (0.8461, -0.0731, -0.4640, -0.0032, -0.0492, -0.0119, 0.7879)],
+         [(0.3561, 0.3972, 0.3904, 0.6966, 0.2286, 0.1596),  # Landsat TM7
+          (-0.3344, -0.3544, -0.4556, 0.6966, -0.0242, -0.2630),
+          (0.2626, 0.2141, 0.0926, 0.0656, -0.7629, -0.5388),
+          (0.0805, -0.0498, 0.1950, -0.1327, 0.5752, -0.7775)],
+         [(0.3029, 0.2786, 0.4733, 0.5599, 0.5080, 0.1872),  # Landsat OLI
+          (-0.2941, -0.2430, -0.5424, 0.7276, 0.0713, -0.1608),
+          (0.1511, 0.1973, 0.3283, 0.3407, -0.7117, -0.4559),
+          (-0.8239, 0.0849, 0.4396, -0.0580, 0.2013, -0.2773)],
+         [(0.4395, 0.5945, 0.2460, 0.3918, 0.3506, 0.2136, 0.2678),  # MODIS
+          (-0.4064, 0.5129, -0.2744, -0.2893, 0.4882, -0.0036, -0.4169),
+          (0.1147, 0.2489, 0.2408, 0.3132, -0.3122, -0.6416, -0.5087)]]
 
 
 
 
 # satellite information
 # satellite information
@@ -167,8 +167,8 @@ def main():
 
 
     # assign "Data Description" field in all four component maps
     # assign "Data Description" field in all four component maps
     for i, comp in enumerate(names):
     for i, comp in enumerate(names):
-        grass.run_command('r.support', map="%s.%d" % (output_basename, i+1),
-                          description="Tasseled Cap %d: %s" % (i+1, comp))
+        grass.run_command('r.support', map="%s.%d" % (output_basename, i + 1),
+                          description="Tasseled Cap %d: %s" % (i + 1, comp))
 
 
     grass.message(_("Tasseled Cap components calculated"))
     grass.message(_("Tasseled Cap components calculated"))
 
 

+ 8 - 7
scripts/m.proj/m.proj.py

@@ -95,10 +95,11 @@ import sys
 import os
 import os
 import threading
 import threading
 from grass.script.utils import separator, parse_key_val
 from grass.script.utils import separator, parse_key_val
-from grass.script import core as grass
+from grass.script import core as gcore
 
 
 
 
 class TrThread(threading.Thread):
 class TrThread(threading.Thread):
+
     def __init__(self, ifs, inf, outf):
     def __init__(self, ifs, inf, outf):
         threading.Thread.__init__(self)
         threading.Thread.__init__(self)
         self.ifs = ifs
         self.ifs = ifs
@@ -150,7 +151,7 @@ def main():
         grass.fatal(_("Output file already exists"))
         grass.fatal(_("Output file already exists"))
 
 
     if not coords and not input:
     if not coords and not input:
-        grass.fatal(_("One of <coordinates> and <input> must be given"))
+        gcore.fatal(_("One of <coordinates> and <input> must be given"))
     if coords and input:
     if coords and input:
         grass.fatal(_(
         grass.fatal(_(
             "Options <coordinates> and <input> are mutually exclusive"))
             "Options <coordinates> and <input> are mutually exclusive"))
@@ -195,7 +196,7 @@ def main():
         in_proj = grass.read_command('g.proj', flags='jf')
         in_proj = grass.read_command('g.proj', flags='jf')
 
 
     in_proj = in_proj.strip()
     in_proj = in_proj.strip()
-    grass.verbose("Input parameters: '%s'" % in_proj)
+    gcore.verbose("Input parameters: '%s'" % in_proj)
 
 
     out_proj = None
     out_proj = None
 
 
@@ -216,12 +217,12 @@ def main():
     if not out_proj:
     if not out_proj:
         grass.fatal(_("Missing output projection parameters "))
         grass.fatal(_("Missing output projection parameters "))
     out_proj = out_proj.strip()
     out_proj = out_proj.strip()
-    grass.verbose("Output parameters: '%s'" % out_proj)
+    gcore.verbose("Output parameters: '%s'" % out_proj)
 
 
     # set up input file
     # set up input file
     if coords:
     if coords:
         x, y = coords.split(',')
         x, y = coords.split(',')
-        tmpfile = grass.tempfile()
+        tmpfile = gcore.tempfile()
         fd = open(tmpfile, "w")
         fd = open(tmpfile, "w")
         fd.write("%s%s%s\n" % (x, ifs, y))
         fd.write("%s%s%s\n" % (x, ifs, y))
         fd.close()
         fd.close()
@@ -233,7 +234,7 @@ def main():
         else:
         else:
             infile = input
             infile = input
             if not os.path.exists(infile):
             if not os.path.exists(infile):
-                grass.fatal(_("Unable to read input data"))
+                gcore.fatal(_("Unable to read input data"))
             inf = file(infile)
             inf = file(infile)
             grass.debug("input file=[%s]" % infile)
             grass.debug("input file=[%s]" % infile)
 
 
@@ -298,5 +299,5 @@ def main():
             "Projection transform probably failed, please investigate"))
             "Projection transform probably failed, please investigate"))
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gcore.parser()
     main()
     main()

+ 50 - 44
scripts/r.blend/r.blend.py

@@ -40,14 +40,13 @@
 #%end
 #%end
 #% flag
 #% flag
 #% key: c
 #% key: c
-#% description: Combine resulting R,G,B layers into single output map 
+#% description: Combine resulting R,G,B layers into single output map
 #%end
 #%end
 
 
-
-import sys
 import os
 import os
 import string
 import string
-import grass.script as grass
+import grass.script as gscript
+
 
 
 def main():
 def main():
     first = options['first']
     first = options['first']
@@ -55,13 +54,13 @@ def main():
     output = options['output']
     output = options['output']
     percent = options['percent']
     percent = options['percent']
 
 
-    mapset = grass.gisenv()['MAPSET']
+    mapset = gscript.gisenv()['MAPSET']
 
 
-    if not grass.overwrite():
-	for ch in ['r','g','b']:
-	    map = '%s.%s' % (output, ch)
-	    if grass.find_file(map, element = 'cell', mapset = mapset)['file']:
-		grass.fatal(_("Raster map <%s> already exists.") % map)
+    if not gscript.overwrite():
+        for ch in ['r', 'g', 'b']:
+            map = '%s.%s' % (output, ch)
+            if gscript.find_file(map, element='cell', mapset=mapset)['file']:
+                gscript.fatal(_("Raster map <%s> already exists.") % map)
 
 
     percent = float(percent)
     percent = float(percent)
     perc_inv = 100.0 - percent
     perc_inv = 100.0 - percent
@@ -69,47 +68,54 @@ def main():
     frac1 = percent / 100.0
     frac1 = percent / 100.0
     frac2 = perc_inv / 100.0
     frac2 = perc_inv / 100.0
 
 
-    grass.message(_("Calculating the three component maps..."))
+    gscript.message(_("Calculating the three component maps..."))
 
 
-    template = string.Template("$$output.$ch = if(isnull($$first), $ch#$$second, if(isnull($$second), $ch#$$first, $$frac1 * $ch#$$first + $$frac2 * $ch#$$second))")
-    cmd = [template.substitute(ch = ch) for ch in ['r','g','b']]
+    template = string.Template("$$output.$ch = "
+                               "if(isnull($$first), $ch#$$second, "
+                               "if(isnull($$second), $ch#$$first, "
+                               "$$frac1 * $ch#$$first + "
+                               "$$frac2 * $ch#$$second))")
+    cmd = [template.substitute(ch=ch) for ch in ['r', 'g', 'b']]
     cmd = ';'.join(cmd)
     cmd = ';'.join(cmd)
 
 
-    grass.mapcalc(cmd,
-		  output = output,
-		  first = first, second = second,
-		  frac1 = frac1, frac2 = frac2)
-
-    for ch in ['r','g','b']:
-	map = "%s.%s" % (output, ch)
-	grass.run_command('r.colors', map = map, color = 'grey255')
-	grass.run_command('r.support', map = map, history="",
-			  title = "Color blend of %s and %s" % (first, second),
-			  description = "generated by r.blend")
-	grass.run_command('r.support', map = map,
-			  history = "r.blend %s channel." % ch)
-	grass.run_command('r.support', map = map,
-			  history = "  %d%% of %s, %d%% of %s" % (percent, first, perc_inv, second))
-	grass.run_command('r.support', map = map, history = "")
-	grass.run_command('r.support', map = map, history = os.environ['CMDLINE'])
-
+    gscript.mapcalc(cmd, output=output, first=first, second=second,
+                    frac1=frac1, frac2=frac2)
+
+    for ch in ['r', 'g', 'b']:
+        map = "%s.%s" % (output, ch)
+        gscript.run_command('r.colors', map=map, color='grey255')
+        gscript.run_command('r.support', map=map, history="",
+                            title="Color blend of %s and %s" % (first, second),
+                            description="generated by r.blend")
+        gscript.run_command('r.support', map=map,
+                            history="r.blend %s channel." % ch)
+        gscript.run_command('r.support', map=map,
+                            history="  %d%% of %s, %d%% of %s" %
+                                    (percent, first, perc_inv, second))
+        gscript.run_command('r.support', map=map, history="")
+        gscript.run_command('r.support', map=map, history=os.environ['CMDLINE'])
 
 
     if flags['c']:
     if flags['c']:
-        grass.run_command('r.composite', r = '%s.r' % output,
-	    g = '%s.g' % output, b = '%s.b' % output, output = output)
-
-	grass.run_command('r.support', map = output, history="",
-	    title = "Color blend of %s and %s" % (first, second),
-	    description = "generated by r.blend")
-	grass.run_command('r.support', map = output,
-	    history = "  %d%% of %s, %d%% of %s" % (percent, first, perc_inv, second))
-	grass.run_command('r.support', map = output, history = "")
-	grass.run_command('r.support', map = output, history = os.environ['CMDLINE'])
+        gscript.run_command('r.composite', r='%s.r' % output,
+                            g='%s.g' % output, b='%s.b' % output,
+                            output=output)
+
+        gscript.run_command('r.support', map=output, history="",
+                            title="Color blend of %s and %s" % (first, second),
+                            description="generated by r.blend")
+        gscript.run_command('r.support', map=output,
+                            history="  %d%% of %s, %d%% of %s" %
+                                    (percent, first, perc_inv, second))
+        gscript.run_command('r.support', map=output, history="")
+        gscript.run_command('r.support', map=output,
+                            history=os.environ['CMDLINE'])
     else:
     else:
-        grass.message(_("Done. Use the following command to visualize the result:"))
-        grass.message(_("d.rgb r=%s.r g=%s.g b=%s.b") % (output, output, output))
+        gscript.message(_("Done. Use the following command to visualize "
+                          "the result:"))
+        gscript.message(_("d.rgb r=%s.r g=%s.g b=%s.b") %
+                        (output, output, output))
 
 
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     main()
     main()

+ 18 - 15
scripts/r.buffer.lowmem/r.buffer.lowmem.py

@@ -53,14 +53,17 @@ scales = {
     'feet': 0.3048,
     'feet': 0.3048,
     'miles': 1609.344,
     'miles': 1609.344,
     'nautmiles': 1852.0
     'nautmiles': 1852.0
-    }
+}
 
 
 # what to do in case of user break:
 # what to do in case of user break:
+
+
 def cleanup():
 def cleanup():
     if grass.find_file(temp_src)['file']:
     if grass.find_file(temp_src)['file']:
-        grass.run_command('g.remove', quiet = True, flags = 'fb', type = 'raster', name = temp_src)
+        grass.run_command('g.remove', quiet=True, flags='fb', type='raster', name=temp_src)
     if grass.find_file(temp_dist)['file']:
     if grass.find_file(temp_dist)['file']:
-        grass.run_command('g.remove', quiet = True, flags = 'fb', type = 'raster', name = temp_dist)
+        grass.run_command('g.remove', quiet=True, flags='fb', type='raster', name=temp_dist)
+
 
 
 def main():
 def main():
     global temp_dist, temp_src
     global temp_dist, temp_src
@@ -75,13 +78,13 @@ def main():
     temp_dist = "r.buffer.tmp.%s.dist" % tmp
     temp_dist = "r.buffer.tmp.%s.dist" % tmp
     temp_src = "r.buffer.tmp.%s.src" % tmp
     temp_src = "r.buffer.tmp.%s.src" % tmp
 
 
-    #check if input file exists
+    # check if input file exists
     if not grass.find_file(input)['file']:
     if not grass.find_file(input)['file']:
         grass.fatal(_("Raster map <%s> not found") % input)
         grass.fatal(_("Raster map <%s> not found") % input)
 
 
     scale = scales[units]
     scale = scales[units]
 
 
-    distances  = distances.split(',')
+    distances = distances.split(',')
     distances1 = [scale * float(d) for d in distances]
     distances1 = [scale * float(d) for d in distances]
     distances2 = [d * d for d in distances1]
     distances2 = [d * d for d in distances1]
 
 
@@ -92,8 +95,8 @@ def main():
     else:
     else:
         metric = 'squared'
         metric = 'squared'
 
 
-    grass.run_command('r.grow.distance',  input = input, metric = metric,
-                      distance = temp_dist, flags = 'm')
+    grass.run_command('r.grow.distance', input=input, metric=metric,
+                      distance=temp_dist, flags='m')
 
 
     if zero:
     if zero:
         exp = "$temp_src = if($input == 0,null(),1)"
         exp = "$temp_src = if($input == 0,null(),1)"
@@ -101,22 +104,22 @@ def main():
         exp = "$temp_src = if(isnull($input),null(),1)"
         exp = "$temp_src = if(isnull($input),null(),1)"
 
 
     grass.message(_("Extracting buffers (1/2)..."))
     grass.message(_("Extracting buffers (1/2)..."))
-    grass.mapcalc(exp, temp_src = temp_src, input = input)
+    grass.mapcalc(exp, temp_src=temp_src, input=input)
 
 
     exp = "$output = if(!isnull($input),$input,%s)"
     exp = "$output = if(!isnull($input),$input,%s)"
     if metric == 'squared':
     if metric == 'squared':
         for n, dist2 in enumerate(distances2):
         for n, dist2 in enumerate(distances2):
-            exp %= "if($dist <= %f,%d,%%s)" % (dist2,n + 2)
+            exp %= "if($dist <= %f,%d,%%s)" % (dist2, n + 2)
     else:
     else:
         for n, dist2 in enumerate(distances1):
         for n, dist2 in enumerate(distances1):
-            exp %= "if($dist <= %f,%d,%%s)" % (dist2,n + 2)
+            exp %= "if($dist <= %f,%d,%%s)" % (dist2, n + 2)
     exp %= "null()"
     exp %= "null()"
 
 
     grass.message(_("Extracting buffers (2/2)..."))
     grass.message(_("Extracting buffers (2/2)..."))
-    grass.mapcalc(exp, output = output, input = temp_src, dist = temp_dist)
+    grass.mapcalc(exp, output=output, input=temp_src, dist=temp_dist)
 
 
-    p = grass.feed_command('r.category', map = output,
-                           separator=':', rules = '-')
+    p = grass.feed_command('r.category', map=output,
+                           separator=':', rules='-')
     p.stdin.write("1:distances calculated from these locations\n")
     p.stdin.write("1:distances calculated from these locations\n")
     d0 = "0"
     d0 = "0"
     for n, d in enumerate(distances):
     for n, d in enumerate(distances):
@@ -125,11 +128,11 @@ def main():
     p.stdin.close()
     p.stdin.close()
     p.wait()
     p.wait()
 
 
-    grass.run_command('r.colors', map = output, color = 'rainbow')
+    grass.run_command('r.colors', map=output, color='rainbow')
 
 
     # write cmd history:
     # write cmd history:
     grass.raster_history(output)
     grass.raster_history(output)
-    
+
 if __name__ == "__main__":
 if __name__ == "__main__":
     options, flags = grass.parser()
     options, flags = grass.parser()
     atexit.register(cleanup)
     atexit.register(cleanup)

+ 88 - 86
scripts/r.colors.stddev/r.colors.stddev.py

@@ -30,18 +30,21 @@
 #% description: Force center at zero
 #% description: Force center at zero
 #%end
 #%end
 
 
-import sys
 import os
 import os
 import atexit
 import atexit
-import grass.script as grass
+
+import grass.script as gscript
+
 
 
 def z(n):
 def z(n):
     return mean + n * stddev
     return mean + n * stddev
 
 
+
 def cleanup():
 def cleanup():
     if tmpmap:
     if tmpmap:
-	grass.run_command('g.remove', flags = 'f', type = 'raster',
-                      name = tmpmap, quiet = True)
+        gscript.run_command('g.remove', flags='f', type='raster',
+                            name=tmpmap, quiet=True)
+
 
 
 def main():
 def main():
     global tmpmap
     global tmpmap
@@ -52,90 +55,89 @@ def main():
     bands = flags['b']
     bands = flags['b']
 
 
     if not zero:
     if not zero:
-	s = grass.read_command('r.univar', flags = 'g', map = map)
-	kv = grass.parse_key_val(s)
-	global mean, stddev
-	mean = float(kv['mean'])
-	stddev = float(kv['stddev'])
-
-	if not bands:
-	    # smooth free floating blue/white/red
-	    rules = '\n'.join([
-		"0% blue",
-		"%f blue"  % z(-2),
-		"%f white" % mean,
-		"%f red"   % z(+2),
-		"100% red"])
-	else:
-	    # banded free floating  black/red/yellow/green/yellow/red/black
-
-	    # reclass with labels only works for category (integer) based maps
-            #r.reclass input="$GIS_OPT_MAP" output="${GIS_OPT_MAP}.stdevs" << EOF
-
-	    # >3 S.D. outliers colored black so they show up in d.histogram w/ white background
-	    rules = '\n'.join([
-		"0% black",
-		"%f black"  % z(-3),
-		"%f red"    % z(-3),
-		"%f red"    % z(-2),
-		"%f yellow" % z(-2),
-		"%f yellow" % z(-1),
-		"%f green"  % z(-1),
-		"%f green"  % z(+1),
-		"%f yellow" % z(+1),
-		"%f yellow" % z(+2),
-		"%f red"    % z(+2),
-		"%f red"    % z(+3),
-		"%f black"  % z(+3),
-		"100% black"])
+        s = gscript.read_command('r.univar', flags='g', map=map)
+        kv = gscript.parse_key_val(s)
+        global mean, stddev
+        mean = float(kv['mean'])
+        stddev = float(kv['stddev'])
+
+        if not bands:
+            # smooth free floating blue/white/red
+            rules = '\n'.join(["0% blue",
+                               "%f blue" % z(-2),
+                               "%f white" % mean,
+                               "%f red" % z(+2),
+                               "100% red"])
+        else:
+            # banded free floating  black/red/yellow/green/yellow/red/black
+
+            # reclass with labels only works for category (integer) based maps
+            # r.reclass input="$GIS_OPT_MAP" output="${GIS_OPT_MAP}.stdevs" <<
+            # EOF
+
+            # >3 S.D. outliers colored black so they show up in d.histogram w/ white background
+            rules = '\n'.join(["0% black",
+                               "%f black" % z(-3),
+                               "%f red" % z(-3),
+                               "%f red" % z(-2),
+                               "%f yellow" % z(-2),
+                               "%f yellow" % z(-1),
+                               "%f green" % z(-1),
+                               "%f green" % z(+1),
+                               "%f yellow" % z(+1),
+                               "%f yellow" % z(+2),
+                               "%f red" % z(+2),
+                               "%f red" % z(+3),
+                               "%f black" % z(+3),
+                               "100% black"])
     else:
     else:
-	tmpmap = "r_col_stdev_abs_%d" % os.getpid()
-	grass.mapcalc("$tmp = abs($map)", tmp = tmpmap, map = map)
-
-	# data centered on 0  (e.g. map of deviations)
-	info = grass.raster_info(tmpmap)
-	maxv = info['max']
-
-	# current r.univar truncates percentage to the base integer
-	s = grass.read_command('r.univar', flags = 'eg', map = map, percentile = [95.45,68.2689,99.7300])
-	kv = grass.parse_key_val(s)
-
-	stddev1 = float(kv['percentile_68_2689'])
-	stddev2 = float(kv['percentile_95_45'])
-	stddev3 = float(kv['percentile_99_73'])
-
-	if not bands:
-	    # zero centered smooth blue/white/red
-	    rules = '\n'.join([
-		"%f blue" % -maxv,
-		"%f blue" % -stddev2,
-		"0 white",
-		"%f red"  % stddev2,
-		"%f red"  % maxv])
-	else:
-	    # zero centered banded  black/red/yellow/green/yellow/red/black
-
-	    # >3 S.D. outliers colored black so they show up in d.histogram w/ white background
-	    rules = '\n'.join([
-		"%f black" % -maxv,
-		"%f black" % -stddev3,
-		"%f red" % -stddev3,
-		"%f red" % -stddev2,
-		"%f yellow" % -stddev2,
-		"%f yellow" % -stddev1,
-		"%f green" % -stddev1,
-		"%f green" % stddev1,
-		"%f yellow" % stddev1,
-		"%f yellow" % stddev2,
-		"%f red" % stddev2,
-		"%f red" % stddev3,
-		"%f black" % stddev3,
-		"%f black" % maxv,
-		])
-
-    grass.write_command('r.colors', map = map, rules = '-', stdin = rules)
+        tmpmap = "r_col_stdev_abs_%d" % os.getpid()
+        gscript.mapcalc("$tmp = abs($map)", tmp=tmpmap, map=map)
+
+        # data centered on 0  (e.g. map of deviations)
+        info = gscript.raster_info(tmpmap)
+        maxv = info['max']
+
+        # current r.univar truncates percentage to the base integer
+        s = gscript.read_command('r.univar', flags='eg', map=map,
+                                 percentile=[95.45,
+                                             68.2689,
+                                             99.7300])
+        kv = gscript.parse_key_val(s)
+
+        stddev1 = float(kv['percentile_68_2689'])
+        stddev2 = float(kv['percentile_95_45'])
+        stddev3 = float(kv['percentile_99_73'])
+
+        if not bands:
+            # zero centered smooth blue/white/red
+            rules = '\n'.join(["%f blue" % -maxv,
+                               "%f blue" % -stddev2,
+                               "0 white",
+                               "%f red" % stddev2,
+                               "%f red" % maxv])
+        else:
+            # zero centered banded  black/red/yellow/green/yellow/red/black
+
+            # >3 S.D. outliers colored black so they show up in d.histogram w/ white background
+            rules = '\n'.join(["%f black" % -maxv,
+                               "%f black" % -stddev3,
+                               "%f red" % -stddev3,
+                               "%f red" % -stddev2,
+                               "%f yellow" % -stddev2,
+                               "%f yellow" % -stddev1,
+                               "%f green" % -stddev1,
+                               "%f green" % stddev1,
+                               "%f yellow" % stddev1,
+                               "%f yellow" % stddev2,
+                               "%f red" % stddev2,
+                               "%f red" % stddev3,
+                               "%f black" % stddev3,
+                               "%f black" % maxv, ])
+
+    gscript.write_command('r.colors', map=map, rules='-', stdin=rules)
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     atexit.register(cleanup)
     atexit.register(cleanup)
     main()
     main()

+ 108 - 81
scripts/r.fillnulls/r.fillnulls.py

@@ -98,15 +98,18 @@ usermask = None
 mapset = None
 mapset = None
 
 
 # what to do in case of user break:
 # what to do in case of user break:
+
+
 def cleanup():
 def cleanup():
-    #delete internal mask and any TMP files:
+    # delete internal mask and any TMP files:
     if len(tmp_vmaps) > 0:
     if len(tmp_vmaps) > 0:
-        grass.run_command('g.remove', quiet = True, flags = 'fb', type = 'vector', name = tmp_vmaps)
+        grass.run_command('g.remove', quiet=True, flags='fb', type='vector', name=tmp_vmaps)
     if len(tmp_rmaps) > 0:
     if len(tmp_rmaps) > 0:
-        grass.run_command('g.remove', quiet = True, flags = 'fb', type = 'raster', name = tmp_rmaps)
+        grass.run_command('g.remove', quiet=True, flags='fb', type='raster', name=tmp_rmaps)
     if usermask and mapset:
     if usermask and mapset:
-        if grass.find_file(usermask, mapset = mapset)['file']:
-            grass.run_command('g.rename', quiet = True, raster = (usermask, 'MASK'), overwrite = True)
+        if grass.find_file(usermask, mapset=mapset)['file']:
+            grass.run_command('g.rename', quiet=True, raster=(usermask, 'MASK'), overwrite=True)
+
 
 
 def main():
 def main():
     global usermask, mapset, tmp_rmaps, tmp_vmaps
     global usermask, mapset, tmp_rmaps, tmp_vmaps
@@ -119,63 +122,63 @@ def main():
     edge = int(options['edge'])
     edge = int(options['edge'])
     segmax = int(options['segmax'])
     segmax = int(options['segmax'])
     npmin = int(options['npmin'])
     npmin = int(options['npmin'])
-    quiet = True # FIXME 
-    
+    quiet = True  # FIXME
+
     mapset = grass.gisenv()['MAPSET']
     mapset = grass.gisenv()['MAPSET']
-    unique = str(os.getpid()) # Shouldn't we use temp name?
+    unique = str(os.getpid())  # Shouldn't we use temp name?
     prefix = 'r_fillnulls_%s_' % unique
     prefix = 'r_fillnulls_%s_' % unique
-    failed_list = list() # a list of failed holes. Caused by issues with v.surf.rst. Connected with #1813
+    failed_list = list()  # a list of failed holes. Caused by issues with v.surf.rst. Connected with #1813
 
 
-    #check if input file exists
+    # check if input file exists
     if not grass.find_file(input)['file']:
     if not grass.find_file(input)['file']:
         grass.fatal(_("Raster map <%s> not found") % input)
         grass.fatal(_("Raster map <%s> not found") % input)
 
 
     # save original region
     # save original region
     reg_org = grass.region()
     reg_org = grass.region()
-    
+
     # check if a MASK is already present
     # check if a MASK is already present
     # and remove it to not interfere with NULL lookup part
     # and remove it to not interfere with NULL lookup part
     # as we don't fill MASKed parts!
     # as we don't fill MASKed parts!
-    if grass.find_file('MASK', mapset = mapset)['file']:
+    if grass.find_file('MASK', mapset=mapset)['file']:
         usermask = "usermask_mask." + unique
         usermask = "usermask_mask." + unique
         grass.message(_("A user raster mask (MASK) is present. Saving it..."))
         grass.message(_("A user raster mask (MASK) is present. Saving it..."))
-        grass.run_command('g.rename', quiet = quiet, raster = ('MASK',usermask))
+        grass.run_command('g.rename', quiet=quiet, raster=('MASK', usermask))
 
 
-    #check if method is rst to use v.surf.rst
+    # check if method is rst to use v.surf.rst
     if method == 'rst':
     if method == 'rst':
         # idea: filter all NULLS and grow that area(s) by 3 pixel, then
         # idea: filter all NULLS and grow that area(s) by 3 pixel, then
         # interpolate from these surrounding 3 pixel edge
         # interpolate from these surrounding 3 pixel edge
         filling = prefix + 'filled'
         filling = prefix + 'filled'
-        
+
         grass.use_temp_region()
         grass.use_temp_region()
-        grass.run_command('g.region', align = input, quiet = quiet)
+        grass.run_command('g.region', align=input, quiet=quiet)
         region = grass.region()
         region = grass.region()
         ns_res = region['nsres']
         ns_res = region['nsres']
         ew_res = region['ewres']
         ew_res = region['ewres']
-        
+
         grass.message(_("Using RST interpolation..."))
         grass.message(_("Using RST interpolation..."))
         grass.message(_("Locating and isolating NULL areas..."))
         grass.message(_("Locating and isolating NULL areas..."))
-        
+
         # creating binary (0/1) map
         # creating binary (0/1) map
         if usermask:
         if usermask:
             grass.message(_("Skipping masked raster parts"))
             grass.message(_("Skipping masked raster parts"))
             grass.mapcalc("$tmp1 = if(isnull($input) && !($mask == 0 || isnull($mask)),1,null())",
             grass.mapcalc("$tmp1 = if(isnull($input) && !($mask == 0 || isnull($mask)),1,null())",
-                tmp1 = prefix + 'nulls', input = input, mask = usermask)
+                          tmp1=prefix + 'nulls', input=input, mask=usermask)
         else:
         else:
             grass.mapcalc("$tmp1 = if(isnull($input),1,null())",
             grass.mapcalc("$tmp1 = if(isnull($input),1,null())",
-                tmp1 = prefix + 'nulls', input = input)
+                          tmp1=prefix + 'nulls', input=input)
         tmp_rmaps.append(prefix + 'nulls')
         tmp_rmaps.append(prefix + 'nulls')
-            
+
         # restoring user's mask, if present
         # restoring user's mask, if present
         # to ignore MASKed original values
         # to ignore MASKed original values
         if usermask:
         if usermask:
             grass.message(_("Restoring user mask (MASK)..."))
             grass.message(_("Restoring user mask (MASK)..."))
             try:
             try:
-                grass.run_command('g.rename', quiet=quiet, raster = (usermask, 'MASK'))
+                grass.run_command('g.rename', quiet=quiet, raster=(usermask, 'MASK'))
             except CalledModuleError:
             except CalledModuleError:
                 grass.warning(_("Failed to restore user MASK!"))
                 grass.warning(_("Failed to restore user MASK!"))
             usermask = None
             usermask = None
-    
+
         # grow identified holes by X pixels
         # grow identified holes by X pixels
         grass.message(_("Growing NULL areas"))
         grass.message(_("Growing NULL areas"))
         tmp_rmaps.append(prefix + 'grown')
         tmp_rmaps.append(prefix + 'grown')
@@ -190,15 +193,21 @@ def main():
         grass.message(_("Assigning IDs to NULL areas"))
         grass.message(_("Assigning IDs to NULL areas"))
         tmp_rmaps.append(prefix + 'clumped')
         tmp_rmaps.append(prefix + 'clumped')
         try:
         try:
-            grass.run_command('r.clump', input=prefix + 'grown', output=prefix + 'clumped', quiet=quiet)
+            grass.run_command(
+                'r.clump',
+                input=prefix +
+                'grown',
+                output=prefix +
+                'clumped',
+                quiet=quiet)
         except CalledModuleError:
         except CalledModuleError:
             grass.fatal(_("abandoned. Removing temporary map, restoring user mask if needed:"))
             grass.fatal(_("abandoned. Removing temporary map, restoring user mask if needed:"))
 
 
         # get a list of unique hole cat's
         # get a list of unique hole cat's
         grass.mapcalc("$out = if(isnull($inp), null(), $clumped)",
         grass.mapcalc("$out = if(isnull($inp), null(), $clumped)",
-                        out = prefix + 'holes', inp = prefix + 'nulls', clumped = prefix + 'clumped')
+                      out=prefix + 'holes', inp=prefix + 'nulls', clumped=prefix + 'clumped')
         tmp_rmaps.append(prefix + 'holes')
         tmp_rmaps.append(prefix + 'holes')
-        
+
         # use new IDs to identify holes
         # use new IDs to identify holes
         try:
         try:
             grass.run_command('r.to.vect', flags='v',
             grass.run_command('r.to.vect', flags='v',
@@ -207,20 +216,26 @@ def main():
         except:
         except:
             grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
             grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
         tmp_vmaps.append(prefix + 'holes')
         tmp_vmaps.append(prefix + 'holes')
-        
+
         # get a list of unique hole cat's
         # get a list of unique hole cat's
         cats_file_name = grass.tempfile(False)
         cats_file_name = grass.tempfile(False)
-        grass.run_command('v.db.select', flags = 'c', map = prefix + 'holes', columns = 'cat', file = cats_file_name, quiet = quiet)
+        grass.run_command(
+            'v.db.select',
+            flags='c',
+            map=prefix + 'holes',
+            columns='cat',
+            file=cats_file_name,
+            quiet=quiet)
         cat_list = list()
         cat_list = list()
         cats_file = file(cats_file_name)
         cats_file = file(cats_file_name)
         for line in cats_file:
         for line in cats_file:
             cat_list.append(line.rstrip('\n'))
             cat_list.append(line.rstrip('\n'))
         cats_file.close()
         cats_file.close()
         os.remove(cats_file_name)
         os.remove(cats_file_name)
-        
+
         if len(cat_list) < 1:
         if len(cat_list) < 1:
             grass.fatal(_("Input map has no holes. Check region settings."))
             grass.fatal(_("Input map has no holes. Check region settings."))
-        
+
         # GTC Hole is NULL area in a raster map
         # GTC Hole is NULL area in a raster map
         grass.message(_("Processing %d map holes") % len(cat_list))
         grass.message(_("Processing %d map holes") % len(cat_list))
         first = True
         first = True
@@ -238,19 +253,20 @@ def main():
             except CalledModuleError:
             except CalledModuleError:
                 grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
                 grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
             tmp_vmaps.append(holename + '_pol')
             tmp_vmaps.append(holename + '_pol')
-            
-            # zoom to specific hole with a buffer of two cells around the hole to remove rest of data
+
+            # zoom to specific hole with a buffer of two cells around the hole to
+            # remove rest of data
             try:
             try:
                 grass.run_command('g.region',
                 grass.run_command('g.region',
-                                  vector=holename + '_pol', align=input, 
-                                  w = 'w-%d' % (edge * 2 * ew_res),
-                                  e = 'e+%d' % (edge * 2 * ew_res), 
-                                  n = 'n+%d' % (edge * 2 * ns_res),
-                                  s = 's-%d' % (edge * 2 * ns_res),
+                                  vector=holename + '_pol', align=input,
+                                  w='w-%d' % (edge * 2 * ew_res),
+                                  e='e+%d' % (edge * 2 * ew_res),
+                                  n='n+%d' % (edge * 2 * ns_res),
+                                  s='s-%d' % (edge * 2 * ns_res),
                                   quiet=quiet)
                                   quiet=quiet)
             except CalledModuleError:
             except CalledModuleError:
                 grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
                 grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
-            
+
             # remove temporary map to not overfill disk
             # remove temporary map to not overfill disk
             try:
             try:
                 grass.run_command('g.remove', flags='fb', type='vector',
                 grass.run_command('g.remove', flags='fb', type='vector',
@@ -258,29 +274,29 @@ def main():
             except CalledModuleError:
             except CalledModuleError:
                 grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
                 grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
             tmp_vmaps.remove(holename + '_pol')
             tmp_vmaps.remove(holename + '_pol')
-            
+
             # copy only data around hole
             # copy only data around hole
             grass.mapcalc("$out = if($inp == $catn, $inp, null())",
             grass.mapcalc("$out = if($inp == $catn, $inp, null())",
-                            out = holename, inp = prefix + 'holes', catn = cat)
+                          out=holename, inp=prefix + 'holes', catn=cat)
             tmp_rmaps.append(holename)
             tmp_rmaps.append(holename)
-            
-            # If here loop is split into two, next part of loop can be run in parallel 
+
+            # If here loop is split into two, next part of loop can be run in parallel
             # (except final result patching)
             # (except final result patching)
             # Downside - on large maps such approach causes large disk usage
             # Downside - on large maps such approach causes large disk usage
-            
+
             # grow hole border to get it's edge area
             # grow hole border to get it's edge area
             tmp_rmaps.append(holename + '_grown')
             tmp_rmaps.append(holename + '_grown')
             try:
             try:
                 grass.run_command('r.grow', input=holename, radius=edge + 0.01,
                 grass.run_command('r.grow', input=holename, radius=edge + 0.01,
-                             old=-1, out=holename + '_grown', quiet=quiet)
+                                  old=-1, out=holename + '_grown', quiet=quiet)
             except CalledModuleError:
             except CalledModuleError:
                 grass.fatal(_("abandoned. Removing temporary map, restoring user mask if needed:"))
                 grass.fatal(_("abandoned. Removing temporary map, restoring user mask if needed:"))
-            
+
             # no idea why r.grow old=-1 doesn't replace existing values with NULL
             # no idea why r.grow old=-1 doesn't replace existing values with NULL
-            grass.mapcalc("$out = if($inp == -1, null(), $dem)", 
-                            out = holename + '_edges', inp = holename + '_grown', dem = input)
+            grass.mapcalc("$out = if($inp == -1, null(), $dem)",
+                          out=holename + '_edges', inp=holename + '_grown', dem=input)
             tmp_rmaps.append(holename + '_edges')
             tmp_rmaps.append(holename + '_edges')
-            
+
             # convert to points for interpolation
             # convert to points for interpolation
             tmp_vmaps.append(holename)
             tmp_vmaps.append(holename)
             try:
             try:
@@ -289,32 +305,32 @@ def main():
                                   type='point', flags='z', quiet=quiet)
                                   type='point', flags='z', quiet=quiet)
             except CalledModuleError:
             except CalledModuleError:
                 grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
                 grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
-            
+
             # count number of points to control segmax parameter for interpolation:
             # count number of points to control segmax parameter for interpolation:
-            pointsnumber = grass.vector_info_topo(map = holename)['points']
+            pointsnumber = grass.vector_info_topo(map=holename)['points']
             grass.verbose(_("Interpolating %d points") % pointsnumber)
             grass.verbose(_("Interpolating %d points") % pointsnumber)
 
 
             if pointsnumber < 2:
             if pointsnumber < 2:
                 grass.verbose(_("No points to interpolate"))
                 grass.verbose(_("No points to interpolate"))
                 failed_list.append(holename)
                 failed_list.append(holename)
                 continue
                 continue
-            
+
             # Avoid v.surf.rst warnings
             # Avoid v.surf.rst warnings
             if pointsnumber < segmax:
             if pointsnumber < segmax:
                 npmin = pointsnumber + 1
                 npmin = pointsnumber + 1
                 segmax = pointsnumber
                 segmax = pointsnumber
-            
+
             # launch v.surf.rst
             # launch v.surf.rst
             tmp_rmaps.append(holename + '_dem')
             tmp_rmaps.append(holename + '_dem')
             try:
             try:
                 grass.run_command('v.surf.rst', quiet=quiet,
                 grass.run_command('v.surf.rst', quiet=quiet,
                                   input=holename, elev=holename + '_dem',
                                   input=holename, elev=holename + '_dem',
-                                  tension=tension, smooth=smooth, 
+                                  tension=tension, smooth=smooth,
                                   segmax=segmax, npmin=npmin)
                                   segmax=segmax, npmin=npmin)
             except CalledModuleError:
             except CalledModuleError:
                 # GTC Hole is NULL area in a raster map
                 # GTC Hole is NULL area in a raster map
                 grass.fatal(_("Failed to fill hole %s") % cat)
                 grass.fatal(_("Failed to fill hole %s") % cat)
-            
+
             # v.surf.rst sometimes fails with exit code 0
             # v.surf.rst sometimes fails with exit code 0
             # related bug #1813
             # related bug #1813
             if not grass.find_file(holename + '_dem')['file']:
             if not grass.find_file(holename + '_dem')['file']:
@@ -326,30 +342,40 @@ def main():
                     tmp_vmaps.remove(holename)
                     tmp_vmaps.remove(holename)
                 except:
                 except:
                     pass
                     pass
-                grass.warning(_("Filling has failed silently. Leaving temporary maps with prefix <%s> for debugging.") % holename)
+                grass.warning(
+                    _("Filling has failed silently. Leaving temporary maps with prefix <%s> for debugging.") %
+                    holename)
                 failed_list.append(holename)
                 failed_list.append(holename)
                 continue
                 continue
-            
+
             # append hole result to interpolated version later used to patch into original DEM
             # append hole result to interpolated version later used to patch into original DEM
             if first:
             if first:
                 tmp_rmaps.append(filling)
                 tmp_rmaps.append(filling)
-                grass.run_command('g.region', align = input, raster = holename + '_dem', quiet = quiet)
-                grass.mapcalc("$out = if(isnull($inp), null(), $dem)", 
-                                out = filling, inp = holename, dem = holename + '_dem')
+                grass.run_command('g.region', align=input, raster=holename + '_dem', quiet=quiet)
+                grass.mapcalc("$out = if(isnull($inp), null(), $dem)",
+                              out=filling, inp=holename, dem=holename + '_dem')
                 first = False
                 first = False
             else:
             else:
                 tmp_rmaps.append(filling + '_tmp')
                 tmp_rmaps.append(filling + '_tmp')
-                grass.run_command('g.region', align = input, raster = (filling, holename + '_dem'), quiet = quiet)
-                grass.mapcalc("$out = if(isnull($inp), if(isnull($fill), null(), $fill), $dem)", 
-                                out = filling + '_tmp', inp = holename, dem = holename + '_dem', fill = filling)
+                grass.run_command(
+                    'g.region', align=input, raster=(
+                        filling, holename + '_dem'), quiet=quiet)
+                grass.mapcalc(
+                    "$out = if(isnull($inp), if(isnull($fill), null(), $fill), $dem)",
+                    out=filling + '_tmp',
+                    inp=holename,
+                    dem=holename + '_dem',
+                    fill=filling)
                 try:
                 try:
                     grass.run_command('g.rename',
                     grass.run_command('g.rename',
                                       raster=(filling + '_tmp', filling),
                                       raster=(filling + '_tmp', filling),
                                       overwrite=True, quiet=quiet)
                                       overwrite=True, quiet=quiet)
                 except CalledModuleError:
                 except CalledModuleError:
-                    grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
-                tmp_rmaps.remove(filling + '_tmp') # this map has been removed. No need for later cleanup.
-            
+                    grass.fatal(
+                        _("abandoned. Removing temporary maps, restoring user mask if needed:"))
+                # this map has been removed. No need for later cleanup.
+                tmp_rmaps.remove(filling + '_tmp')
+
             # remove temporary maps to not overfill disk
             # remove temporary maps to not overfill disk
             try:
             try:
                 tmp_rmaps.remove(holename)
                 tmp_rmaps.remove(holename)
@@ -376,28 +402,28 @@ def main():
                                   type='vector', name=holename)
                                   type='vector', name=holename)
             except CalledModuleError:
             except CalledModuleError:
                 grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
                 grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
-    
-    #check if method is different from rst to use r.resamp.bspline
+
+    # check if method is different from rst to use r.resamp.bspline
     if method != 'rst':
     if method != 'rst':
         grass.message(_("Using %s bspline interpolation") % method)
         grass.message(_("Using %s bspline interpolation") % method)
 
 
         # clone current region
         # clone current region
         grass.use_temp_region()
         grass.use_temp_region()
-        grass.run_command('g.region', align = input)
+        grass.run_command('g.region', align=input)
 
 
         reg = grass.region()
         reg = grass.region()
         # launch r.resamp.bspline
         # launch r.resamp.bspline
         tmp_rmaps.append(prefix + 'filled')
         tmp_rmaps.append(prefix + 'filled')
         if usermask:
         if usermask:
-            grass.run_command('r.resamp.bspline', input = input, mask = usermask,
-                output = prefix + 'filled', method = method, 
-                ew_step = 3 * reg['ewres'], ns_step = 3 * reg['nsres'], 
-                lambda_ = 0.01, flags = 'n')
+            grass.run_command('r.resamp.bspline', input=input, mask=usermask,
+                              output=prefix + 'filled', method=method,
+                              ew_step=3 * reg['ewres'], ns_step=3 * reg['nsres'],
+                              lambda_=0.01, flags='n')
         else:
         else:
-            grass.run_command('r.resamp.bspline', input = input,
-                output = prefix + 'filled', method = method, 
-                ew_step = 3 * reg['ewres'], ns_step = 3 * reg['nsres'], 
-                lambda_ = 0.01, flags = 'n')
+            grass.run_command('r.resamp.bspline', input=input,
+                              output=prefix + 'filled', method=method,
+                              ew_step=3 * reg['ewres'], ns_step=3 * reg['nsres'],
+                              lambda_=0.01, flags='n')
 
 
     # restoring user's mask, if present:
     # restoring user's mask, if present:
     if usermask:
     if usermask:
@@ -409,13 +435,13 @@ def main():
         usermask = None
         usermask = None
 
 
     # set region to original extents, align to input
     # set region to original extents, align to input
-    grass.run_command('g.region', n = reg_org['n'], s = reg_org['s'], 
-                    e = reg_org['e'], w = reg_org['w'], align = input)
+    grass.run_command('g.region', n=reg_org['n'], s=reg_org['s'],
+                      e=reg_org['e'], w=reg_org['w'], align=input)
 
 
     # patch orig and fill map
     # patch orig and fill map
     grass.message(_("Patching fill data into NULL areas..."))
     grass.message(_("Patching fill data into NULL areas..."))
     # we can use --o here as g.parser already checks on startup
     # we can use --o here as g.parser already checks on startup
-    grass.run_command('r.patch', input = (input,prefix + 'filled'), output = output, overwrite = True)
+    grass.run_command('r.patch', input=(input, prefix + 'filled'), output=output, overwrite=True)
 
 
     # restore the real region
     # restore the real region
     grass.del_temp_region()
     grass.del_temp_region()
@@ -424,9 +450,10 @@ def main():
 
 
     # write cmd history:
     # write cmd history:
     grass.raster_history(output)
     grass.raster_history(output)
-    
+
     if len(failed_list) > 0:
     if len(failed_list) > 0:
-        grass.warning(_("Following holes where not filled. Temporary maps with are left in place to allow examination of unfilled holes"))
+        grass.warning(
+            _("Following holes where not filled. Temporary maps with are left in place to allow examination of unfilled holes"))
         outlist = failed_list[0]
         outlist = failed_list[0]
         for hole in failed_list[1:]:
         for hole in failed_list[1:]:
             outlist = ', ' + outlist
             outlist = ', ' + outlist

+ 7 - 6
scripts/r.grow/r.grow.py

@@ -72,8 +72,9 @@ from grass.exceptions import CalledModuleError
 def cleanup():
 def cleanup():
     for map in [temp_dist, temp_val]:
     for map in [temp_dist, temp_val]:
         if map:
         if map:
-            grass.run_command('g.remove', flags = 'fb', quiet = True,
-                              type='rast', name = map)
+            grass.run_command('g.remove', flags='fb', quiet=True,
+                              type='rast', name=map)
+
 
 
 def main():
 def main():
     global temp_dist, temp_val
     global temp_dist, temp_val
@@ -108,7 +109,7 @@ def main():
         metric = 'squared'
         metric = 'squared'
         radius = radius * radius
         radius = radius * radius
 
 
-    #check if input file exists
+    # check if input file exists
     if not grass.find_file(input)['file']:
     if not grass.find_file(input)['file']:
         grass.fatal(_("Raster map <%s> not found") % input)
         grass.fatal(_("Raster map <%s> not found") % input)
 
 
@@ -120,10 +121,10 @@ def main():
 
 
     grass.mapcalc(
     grass.mapcalc(
         "$output = if(!isnull($input),$old,if($dist < $radius,$new,null()))",
         "$output = if(!isnull($input),$old,if($dist < $radius,$new,null()))",
-        output = output, input = input, radius = radius,
-        old = old, new = new, dist = temp_dist)
+        output=output, input=input, radius=radius,
+        old=old, new=new, dist=temp_dist)
 
 
-    grass.run_command('r.colors', map = output, raster = input)
+    grass.run_command('r.colors', map=output, raster=input)
 
 
     # write cmd history:
     # write cmd history:
     grass.raster_history(output)
     grass.raster_history(output)

+ 15 - 6
scripts/r.import/r.import.py

@@ -161,7 +161,8 @@ def main():
         if tgtres_value <= 0:
         if tgtres_value <= 0:
             grass.fatal(_("Resolution value can't be smaller than 0"))
             grass.fatal(_("Resolution value can't be smaller than 0"))
     elif tgtres == 'value':
     elif tgtres == 'value':
-         grass.fatal(_("Please provide the resolution for the imported dataset or change to 'estimated' resolution"))
+        grass.fatal(
+            _("Please provide the resolution for the imported dataset or change to 'estimated' resolution"))
 
 
     grassenv = grass.gisenv()
     grassenv = grass.gisenv()
     tgtloc = grassenv['LOCATION_NAME']
     tgtloc = grassenv['LOCATION_NAME']
@@ -211,14 +212,18 @@ def main():
             parameters['band'] = bands
             parameters['band'] = bands
         try:
         try:
             grass.run_command('r.in.gdal', **parameters)
             grass.run_command('r.in.gdal', **parameters)
-            grass.verbose(_("Input <%s> successfully imported without reprojection") % GDALdatasource)
+            grass.verbose(
+                _("Input <%s> successfully imported without reprojection") %
+                GDALdatasource)
             return 0
             return 0
         except CalledModuleError as e:
         except CalledModuleError as e:
             grass.fatal(_("Unable to import GDAL dataset <%s>") % GDALdatasource)
             grass.fatal(_("Unable to import GDAL dataset <%s>") % GDALdatasource)
-    
+
     # make sure target is not xy
     # make sure target is not xy
     if grass.parse_command('g.proj', flags='g')['name'] == 'xy_location_unprojected':
     if grass.parse_command('g.proj', flags='g')['name'] == 'xy_location_unprojected':
-        grass.fatal(_("Coordinate reference system not available for current location <%s>") % tgtloc)
+        grass.fatal(
+            _("Coordinate reference system not available for current location <%s>") %
+            tgtloc)
 
 
     # switch to temp location
     # switch to temp location
     os.environ['GISRC'] = str(SRCGISRC)
     os.environ['GISRC'] = str(SRCGISRC)
@@ -327,7 +332,9 @@ def main():
         grass.run_command('g.remove', type='vector', name=vreg,
         grass.run_command('g.remove', type='vector', name=vreg,
                           flags='f', quiet=True)
                           flags='f', quiet=True)
 
 
-        grass.message(_("Estimated target resolution for input band <{out}>: {res}").format(out=outfile, res=estres))
+        grass.message(
+            _("Estimated target resolution for input band <{out}>: {res}").format(
+                out=outfile, res=estres))
         if flags['e']:
         if flags['e']:
             continue
             continue
 
 
@@ -340,7 +347,9 @@ def main():
             res = estres
             res = estres
         elif tgtres == 'value':
         elif tgtres == 'value':
             res = tgtres_value
             res = tgtres_value
-            grass.message(_("Using given resolution for input band <{out}>: {res}").format(out=outfile, res=res))
+            grass.message(
+                _("Using given resolution for input band <{out}>: {res}").format(
+                    out=outfile, res=res))
             # align to requested resolution
             # align to requested resolution
             grass.run_command('g.region', res=res, flags='a')
             grass.run_command('g.region', res=res, flags='a')
         else:
         else:

+ 39 - 38
scripts/r.in.aster/r.in.aster.py

@@ -5,9 +5,9 @@
 # MODULE:    r_in_aster.py
 # MODULE:    r_in_aster.py
 # AUTHOR(S): Michael Barton (michael.barton@asu.edu) and
 # AUTHOR(S): Michael Barton (michael.barton@asu.edu) and
 #               Glynn Clements (glynn@gclements.plus.com)
 #               Glynn Clements (glynn@gclements.plus.com)
-#               Based on r.in.aster bash script for GRASS 
+#               Based on r.in.aster bash script for GRASS
 #               by Michael Barton and Paul Kelly
 #               by Michael Barton and Paul Kelly
-# PURPOSE:   Rectifies, georeferences, & imports Terra-ASTER imagery 
+# PURPOSE:   Rectifies, georeferences, & imports Terra-ASTER imagery
 #               using gdalwarp
 #               using gdalwarp
 # COPYRIGHT: (C) 2008 by the GRASS Development Team
 # COPYRIGHT: (C) 2008 by the GRASS Development Team
 #
 #
@@ -57,16 +57,16 @@ import grass.script as grass
 
 
 bands = {
 bands = {
     'L1A': {
     'L1A': {
-        '1':  "VNIR_Band1:ImageData",
-        '2':  "VNIR_Band2:ImageData",
+        '1': "VNIR_Band1:ImageData",
+        '2': "VNIR_Band2:ImageData",
         '3n': "VNIR_Band3N:ImageData",
         '3n': "VNIR_Band3N:ImageData",
         '3b': "VNIR_Band3B:ImageData",
         '3b': "VNIR_Band3B:ImageData",
-        '4':  "SWIR_Band4:ImageData",
-        '5':  "SWIR_Band5:ImageData",
-        '6':  "SWIR_Band6:ImageData",
-        '7':  "SWIR_Band7:ImageData",
-        '8':  "SWIR_Band8:ImageData",
-        '9':  "SWIR_Band9:ImageData",
+        '4': "SWIR_Band4:ImageData",
+        '5': "SWIR_Band5:ImageData",
+        '6': "SWIR_Band6:ImageData",
+        '7': "SWIR_Band7:ImageData",
+        '8': "SWIR_Band8:ImageData",
+        '9': "SWIR_Band9:ImageData",
         '10': "TIR_Band10:ImageData",
         '10': "TIR_Band10:ImageData",
         '11': "TIR_Band11:ImageData",
         '11': "TIR_Band11:ImageData",
         '12': "TIR_Band12:ImageData",
         '12': "TIR_Band12:ImageData",
@@ -74,16 +74,16 @@ bands = {
         '14': "TIR_Band14:ImageData"
         '14': "TIR_Band14:ImageData"
     },
     },
     'L1B': {
     'L1B': {
-        '1':  "VNIR_Swath:ImageData1",
-        '2':  "VNIR_Swath:ImageData2",
+        '1': "VNIR_Swath:ImageData1",
+        '2': "VNIR_Swath:ImageData2",
         '3n': "VNIR_Swath:ImageData3N",
         '3n': "VNIR_Swath:ImageData3N",
         '3b': "VNIR_Swath:ImageData3B",
         '3b': "VNIR_Swath:ImageData3B",
-        '4':  "SWIR_Swath:ImageData4",
-        '5':  "SWIR_Swath:ImageData5",
-        '6':  "SWIR_Swath:ImageData6",
-        '7':  "SWIR_Swath:ImageData7",
-        '8':  "SWIR_Swath:ImageData8",
-        '9':  "SWIR_Swath:ImageData9",
+        '4': "SWIR_Swath:ImageData4",
+        '5': "SWIR_Swath:ImageData5",
+        '6': "SWIR_Swath:ImageData6",
+        '7': "SWIR_Swath:ImageData7",
+        '8': "SWIR_Swath:ImageData8",
+        '9': "SWIR_Swath:ImageData9",
         '10': "TIR_Swath:ImageData10",
         '10': "TIR_Swath:ImageData10",
         '11': "TIR_Swath:ImageData11",
         '11': "TIR_Swath:ImageData11",
         '12': "TIR_Swath:ImageData12",
         '12': "TIR_Swath:ImageData12",
@@ -92,35 +92,35 @@ bands = {
     }
     }
 }
 }
 
 
+
 def main():
 def main():
     input = options['input']
     input = options['input']
     proctype = options['proctype']
     proctype = options['proctype']
     output = options['output']
     output = options['output']
     band = options['band']
     band = options['band']
 
 
-    #check whether gdalwarp is in path and executable
+    # check whether gdalwarp is in path and executable
     if not grass.find_program('gdalwarp', '--help'):
     if not grass.find_program('gdalwarp', '--help'):
         grass.fatal(_("gdalwarp is not in the path and executable"))
         grass.fatal(_("gdalwarp is not in the path and executable"))
 
 
-    #create temporary file to hold gdalwarp output before importing to GRASS
-    tempfile = grass.read_command("g.tempfile", pid = os.getpid()).strip() + '.tif'
+    # create temporary file to hold gdalwarp output before importing to GRASS
+    tempfile = grass.read_command("g.tempfile", pid=os.getpid()).strip() + '.tif'
 
 
-    #get projection information for current GRASS location
-    proj = grass.read_command('g.proj', flags = 'jf').strip()
+    # get projection information for current GRASS location
+    proj = grass.read_command('g.proj', flags='jf').strip()
 
 
-    #currently only runs in projected location
+    # currently only runs in projected location
     if "XY location" in proj:
     if "XY location" in proj:
-      grass.fatal(_("This module needs to be run in a projected location (found: %s)") % proj)
-
+        grass.fatal(_("This module needs to be run in a projected location (found: %s)") % proj)
 
 
-    #process list of bands
-    allbands = ['1','2','3n','3b','4','5','6','7','8','9','10','11','12','13','14']
+    # process list of bands
+    allbands = ['1', '2', '3n', '3b', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
     if band == 'all':
     if band == 'all':
         bandlist = allbands
         bandlist = allbands
     else:
     else:
         bandlist = band.split(',')
         bandlist = band.split(',')
 
 
-    #initialize datasets for L1A and L1B
+    # initialize datasets for L1A and L1B
     if proctype in ["L1A", "L1B"]:
     if proctype in ["L1A", "L1B"]:
         for band in bandlist:
         for band in bandlist:
             if band in allbands:
             if band in allbands:
@@ -129,36 +129,37 @@ def main():
                 import_aster(proj, srcfile, tempfile, band)
                 import_aster(proj, srcfile, tempfile, band)
             else:
             else:
                 grass.fatal(_('band %s is not an available Terra/ASTER band') % band)
                 grass.fatal(_('band %s is not an available Terra/ASTER band') % band)
-    elif proctype == "DEM": 
+    elif proctype == "DEM":
         srcfile = input
         srcfile = input
         import_aster(proj, srcfile, tempfile, "DEM")
         import_aster(proj, srcfile, tempfile, "DEM")
 
 
-    #cleanup
+    # cleanup
     grass.message(_("Cleaning up ..."))
     grass.message(_("Cleaning up ..."))
     grass.try_remove(tempfile)
     grass.try_remove(tempfile)
     grass.message(_("Done."))
     grass.message(_("Done."))
 
 
     return
     return
 
 
+
 def import_aster(proj, srcfile, tempfile, band):
 def import_aster(proj, srcfile, tempfile, band):
-    #run gdalwarp with selected options (must be in $PATH)
-    #to translate aster image to geotiff
+    # run gdalwarp with selected options (must be in $PATH)
+    # to translate aster image to geotiff
     grass.message(_("Georeferencing aster image ..."))
     grass.message(_("Georeferencing aster image ..."))
     grass.debug("gdalwarp -t_srs %s %s %s" % (proj, srcfile, tempfile))
     grass.debug("gdalwarp -t_srs %s %s %s" % (proj, srcfile, tempfile))
 
 
     if platform.system() == "Darwin":
     if platform.system() == "Darwin":
-        cmd = ["arch", "-i386", "gdalwarp", "-t_srs", proj, srcfile, tempfile ]
+        cmd = ["arch", "-i386", "gdalwarp", "-t_srs", proj, srcfile, tempfile]
     else:
     else:
-        cmd = ["gdalwarp", "-t_srs", proj, srcfile, tempfile ]
+        cmd = ["gdalwarp", "-t_srs", proj, srcfile, tempfile]
     p = grass.call(cmd)
     p = grass.call(cmd)
     if p != 0:
     if p != 0:
-        #check to see if gdalwarp executed properly
+        # check to see if gdalwarp executed properly
         return
         return
 
 
-    #import geotiff to GRASS
+    # import geotiff to GRASS
     grass.message(_("Importing into GRASS ..."))
     grass.message(_("Importing into GRASS ..."))
     outfile = "%s.%s" % (output, band)
     outfile = "%s.%s" % (output, band)
-    grass.run_command("r.in.gdal", input = tempfile, output = outfile)
+    grass.run_command("r.in.gdal", input=tempfile, output=outfile)
 
 
     # write cmd history
     # write cmd history
     grass.raster_history(outfile)
     grass.raster_history(outfile)

+ 43 - 42
scripts/r.in.srtm/r.in.srtm.py

@@ -19,18 +19,18 @@
 # Aug 2004: modified to accept files from other directories
 # Aug 2004: modified to accept files from other directories
 #           (by H. Bowman)
 #           (by H. Bowman)
 # June 2005: added flag to read in US 1-arcsec tiles (H. Bowman)
 # June 2005: added flag to read in US 1-arcsec tiles (H. Bowman)
-# April 2006: links updated from ftp://e0dps01u.ecs.nasa.gov/srtm/             
+# April 2006: links updated from ftp://e0dps01u.ecs.nasa.gov/srtm/
 #             to current links below
 #             to current links below
 # October 2008: Converted to Python by Glynn Clements
 # October 2008: Converted to Python by Glynn Clements
 #########################
 #########################
-#Derived from:
+# Derived from:
 # ftp://e0srp01u.ecs.nasa.gov/srtm/version1/Documentation/Notes_for_ARCInfo_users.txt
 # ftp://e0srp01u.ecs.nasa.gov/srtm/version1/Documentation/Notes_for_ARCInfo_users.txt
 #     (note: document was updated silently end of 2003)
 #     (note: document was updated silently end of 2003)
 #
 #
 # ftp://e0srp01u.ecs.nasa.gov/srtm/version1/Documentation/SRTM_Topo.txt
 # ftp://e0srp01u.ecs.nasa.gov/srtm/version1/Documentation/SRTM_Topo.txt
 #  "3.0 Data Formats
 #  "3.0 Data Formats
 #  [...]
 #  [...]
-#  To be more exact, these coordinates refer to the geometric center of 
+#  To be more exact, these coordinates refer to the geometric center of
 #  the lower left pixel, which in the case of SRTM-1 data will be about
 #  the lower left pixel, which in the case of SRTM-1 data will be about
 #  30 meters in extent."
 #  30 meters in extent."
 #
 #
@@ -40,7 +40,7 @@
 #
 #
 #- BIL uses *center* of the UL (!) pixel:
 #- BIL uses *center* of the UL (!) pixel:
 #      http://downloads.esri.com/support/whitepapers/other_/eximgav.pdf
 #      http://downloads.esri.com/support/whitepapers/other_/eximgav.pdf
-#  
+#
 #- GDAL uses *corners* of pixels for its coordinates.
 #- GDAL uses *corners* of pixels for its coordinates.
 #
 #
 # NOTE: Even, if small difference: SRTM is referenced to EGM96, not WGS84 ellps
 # NOTE: Even, if small difference: SRTM is referenced to EGM96, not WGS84 ellps
@@ -116,12 +116,13 @@ from grass.exceptions import CalledModuleError
 
 
 def cleanup():
 def cleanup():
     if not in_temp:
     if not in_temp:
-	return
+        return
     for ext in ['.bil', '.hdr', '.prj', '.hgt.zip']:
     for ext in ['.bil', '.hdr', '.prj', '.hgt.zip']:
-	grass.try_remove(tile + ext)
+        grass.try_remove(tile + ext)
     os.chdir('..')
     os.chdir('..')
     grass.try_rmdir(tmpdir)
     grass.try_rmdir(tmpdir)
 
 
+
 def main():
 def main():
     global tile, tmpdir, in_temp
     global tile, tmpdir, in_temp
 
 
@@ -131,55 +132,55 @@ def main():
     output = options['output']
     output = options['output']
     one = flags['1']
     one = flags['1']
 
 
-    #are we in LatLong location?
+    # are we in LatLong location?
     s = grass.read_command("g.proj", flags='j')
     s = grass.read_command("g.proj", flags='j')
     kv = grass.parse_key_val(s)
     kv = grass.parse_key_val(s)
     if kv['+proj'] != 'longlat':
     if kv['+proj'] != 'longlat':
-	grass.fatal(_("This module only operates in LatLong locations"))
+        grass.fatal(_("This module only operates in LatLong locations"))
 
 
     # use these from now on:
     # use these from now on:
     infile = input
     infile = input
     while infile[-4:].lower() in ['.hgt', '.zip']:
     while infile[-4:].lower() in ['.hgt', '.zip']:
-	infile = infile[:-4]
+        infile = infile[:-4]
     (fdir, tile) = os.path.split(infile)
     (fdir, tile) = os.path.split(infile)
 
 
     if not output:
     if not output:
-	tileout = tile
+        tileout = tile
     else:
     else:
-	tileout = output
+        tileout = output
 
 
     zipfile = infile + ".hgt.zip"
     zipfile = infile + ".hgt.zip"
     hgtfile = os.path.join(fdir, tile[:7] + ".hgt")
     hgtfile = os.path.join(fdir, tile[:7] + ".hgt")
     if os.path.isfile(zipfile):
     if os.path.isfile(zipfile):
-        #### check if we have unzip
-	if not grass.find_program('unzip'):
-	    grass.fatal(_('The "unzip" program is required, please install it first'))
-
-	# really a ZIP file?
-	# make it quiet in a safe way (just in case -qq isn't portable)
-	tenv = os.environ.copy()
-	tenv['UNZIP'] = '-qq'
-	if grass.call(['unzip', '-t', zipfile], env = tenv) != 0:
-	    grass.fatal(_("'%s' does not appear to be a valid zip file.") % zipfile)
-
-	is_zip = True
+        # check if we have unzip
+        if not grass.find_program('unzip'):
+            grass.fatal(_('The "unzip" program is required, please install it first'))
+
+        # really a ZIP file?
+        # make it quiet in a safe way (just in case -qq isn't portable)
+        tenv = os.environ.copy()
+        tenv['UNZIP'] = '-qq'
+        if grass.call(['unzip', '-t', zipfile], env=tenv) != 0:
+            grass.fatal(_("'%s' does not appear to be a valid zip file.") % zipfile)
+
+        is_zip = True
     elif os.path.isfile(hgtfile):
     elif os.path.isfile(hgtfile):
-	# try and see if it's already unzipped
-	is_zip = False
+        # try and see if it's already unzipped
+        is_zip = False
     else:
     else:
-	grass.fatal(_("File '%s' or '%s' not found") % (zipfile, hgtfile))
+        grass.fatal(_("File '%s' or '%s' not found") % (zipfile, hgtfile))
 
 
-    #make a temporary directory
+    # make a temporary directory
     tmpdir = grass.tempfile()
     tmpdir = grass.tempfile()
     grass.try_remove(tmpdir)
     grass.try_remove(tmpdir)
     os.mkdir(tmpdir)
     os.mkdir(tmpdir)
 
 
     if is_zip:
     if is_zip:
-	shutil.copyfile(zipfile, os.path.join(tmpdir, tile + ".hgt.zip"))
+        shutil.copyfile(zipfile, os.path.join(tmpdir, tile + ".hgt.zip"))
     else:
     else:
-	shutil.copyfile(hgtfile, os.path.join(tmpdir, tile + ".hgt"))
+        shutil.copyfile(hgtfile, os.path.join(tmpdir, tile + ".hgt"))
 
 
-    #change to temporary directory
+    # change to temporary directory
     os.chdir(tmpdir)
     os.chdir(tmpdir)
     in_temp = True
     in_temp = True
 
 
@@ -188,26 +189,26 @@ def main():
     bilfile = tile + ".bil"
     bilfile = tile + ".bil"
 
 
     if is_zip:
     if is_zip:
-        #unzip & rename data file:
-	grass.message(_("Extracting '%s'...") % infile)
-	if grass.call(['unzip', zipfile], env = tenv) != 0:
-	    grass.fatal(_("Unable to unzip file."))
+        # unzip & rename data file:
+        grass.message(_("Extracting '%s'...") % infile)
+        if grass.call(['unzip', zipfile], env=tenv) != 0:
+            grass.fatal(_("Unable to unzip file."))
 
 
     grass.message(_("Converting input file to BIL..."))
     grass.message(_("Converting input file to BIL..."))
     os.rename(hgtfile, bilfile)
     os.rename(hgtfile, bilfile)
 
 
     north = tile[0]
     north = tile[0]
-    ll_latitude  = int(tile[1:3])
+    ll_latitude = int(tile[1:3])
     east = tile[3]
     east = tile[3]
     ll_longitude = int(tile[4:7])
     ll_longitude = int(tile[4:7])
 
 
     # are we on the southern hemisphere? If yes, make LATITUDE negative.
     # are we on the southern hemisphere? If yes, make LATITUDE negative.
     if north == "S":
     if north == "S":
-	ll_latitude *= -1
+        ll_latitude *= -1
 
 
     # are we west of Greenwich? If yes, make LONGITUDE negative.
     # are we west of Greenwich? If yes, make LONGITUDE negative.
     if east == "W":
     if east == "W":
-	ll_longitude *= -1
+        ll_longitude *= -1
 
 
     # Calculate Upper Left from Lower Left
     # Calculate Upper Left from Lower Left
     ulxmap = "%.1f" % ll_longitude
     ulxmap = "%.1f" % ll_longitude
@@ -215,10 +216,10 @@ def main():
     ulymap = "%.1f" % (ll_latitude + 1)
     ulymap = "%.1f" % (ll_latitude + 1)
 
 
     if not one:
     if not one:
-	tmpl = tmpl3sec
+        tmpl = tmpl3sec
     else:
     else:
-	grass.message(_("Attempting to import 1-arcsec data."))
-	tmpl = tmpl1sec
+        grass.message(_("Attempting to import 1-arcsec data."))
+        tmpl = tmpl1sec
 
 
     header = tmpl % (ulxmap, ulymap)
     header = tmpl % (ulxmap, ulymap)
     hdrfile = tile + '.hdr'
     hdrfile = tile + '.hdr'
@@ -226,7 +227,7 @@ def main():
     outf.write(header)
     outf.write(header)
     outf.close()
     outf.close()
 
 
-    #create prj file: To be precise, we would need EGS96! But who really cares...
+    # create prj file: To be precise, we would need EGS96! But who really cares...
     prjfile = tile + '.prj'
     prjfile = tile + '.prj'
     outf = file(prjfile, 'w')
     outf = file(prjfile, 'w')
     outf.write(proj)
     outf.write(proj)
@@ -238,7 +239,7 @@ def main():
         grass.fatal(_("Unable to import data"))
         grass.fatal(_("Unable to import data"))
 
 
     # nice color table
     # nice color table
-    grass.run_command('r.colors', map = tileout, color = 'srtm')
+    grass.run_command('r.colors', map=tileout, color='srtm')
 
 
     # write cmd history:
     # write cmd history:
     grass.raster_history(tileout)
     grass.raster_history(tileout)

+ 14 - 12
scripts/r.in.wms/r.in.wms.py

@@ -58,8 +58,8 @@ This program is free software under the GNU General Public License
 #%option
 #%option
 #% key: srs
 #% key: srs
 #% type: integer
 #% type: integer
-#% description: EPSG code of requested source projection 
-#% answer:4326 
+#% description: EPSG code of requested source projection
+#% answer:4326
 #% guisection: Request
 #% guisection: Request
 #%end
 #%end
 
 
@@ -178,29 +178,31 @@ sys.path.insert(1, os.path.join(os.path.dirname(sys.path[0]), 'etc', 'r.in.wms')
 
 
 import grass.script as grass
 import grass.script as grass
 
 
+
 def GetRegionParams(opt_region):
 def GetRegionParams(opt_region):
 
 
-    # set region 
+    # set region
     if opt_region:
     if opt_region:
         reg_spl = opt_region.strip().split('@', 1)
         reg_spl = opt_region.strip().split('@', 1)
         reg_mapset = '.'
         reg_mapset = '.'
         if len(reg_spl) > 1:
         if len(reg_spl) > 1:
             reg_mapset = reg_spl[1]
             reg_mapset = reg_spl[1]
-            
-        if not grass.find_file(name = reg_spl[0], element = 'windows', mapset = reg_mapset)['name']:
-             grass.fatal(_("Region <%s> not found") % opt_region)
-    
+
+        if not grass.find_file(name=reg_spl[0], element='windows', mapset=reg_mapset)['name']:
+            grass.fatal(_("Region <%s> not found") % opt_region)
+
     if opt_region:
     if opt_region:
         s = grass.read_command('g.region',
         s = grass.read_command('g.region',
-                                quiet = True,
-                                flags = 'ug',
-                                region = opt_region)
-        region_params = grass.parse_key_val(s, val_type = float)
+                               quiet=True,
+                               flags='ug',
+                               region=opt_region)
+        region_params = grass.parse_key_val(s, val_type=float)
     else:
     else:
         region_params = grass.region()
         region_params = grass.region()
 
 
     return region_params
     return region_params
 
 
+
 def main():
 def main():
 
 
     if 'GRASS' in options['driver']:
     if 'GRASS' in options['driver']:
@@ -211,7 +213,7 @@ def main():
         grass.debug("Using GDAL WMS driver")
         grass.debug("Using GDAL WMS driver")
         from wms_gdal_drv import WMSGdalDrv
         from wms_gdal_drv import WMSGdalDrv
         wms = WMSGdalDrv()
         wms = WMSGdalDrv()
-    
+
     if flags['c']:
     if flags['c']:
         wms.GetCapabilities(options)
         wms.GetCapabilities(options)
     else:
     else:

+ 8 - 7
scripts/r.in.wms/srs.py

@@ -1,5 +1,5 @@
 """!
 """!
-@brief WMS, WMTS and NASA OnEarth drivers implemented in GRASS using GDAL Python bindings. 
+@brief WMS, WMTS and NASA OnEarth drivers implemented in GRASS using GDAL Python bindings.
 
 
 List of classes:
 List of classes:
  - srs.py::Srs
  - srs.py::Srs
@@ -32,6 +32,7 @@ class Srs:
           * urn:ogc:def:crs:EPSG:4326
           * urn:ogc:def:crs:EPSG:4326
         :param string axisorder: Force / override axisorder ('xy' or 'yx')
         :param string axisorder: Force / override axisorder ('xy' or 'yx')
     """
     """
+
     def __init__(self, srs):
     def __init__(self, srs):
         self.id = srs
         self.id = srs
         self.naming_authority = None
         self.naming_authority = None
@@ -45,7 +46,7 @@ class Srs:
 
 
         values = self.id.split(':')
         values = self.id.split(':')
 
 
-        if self.id.find('/def/crs/') != -1: # URI Style 1
+        if self.id.find('/def/crs/') != -1:  # URI Style 1
             self.encoding = "uri"
             self.encoding = "uri"
             vals = self.id.split('/')
             vals = self.id.split('/')
             self.authority = vals[5].upper()
             self.authority = vals[5].upper()
@@ -84,7 +85,7 @@ class Srs:
             self.code = int(values[1])
             self.code = int(values[1])
 
 
         if self.code in axisorder_yx:
         if self.code in axisorder_yx:
-                self.axisorder = 'yx'
+            self.axisorder = 'yx'
 
 
     def getcode(self):
     def getcode(self):
         """Create for example "EPSG:4326" string and return back
         """Create for example "EPSG:4326" string and return back
@@ -101,10 +102,10 @@ class Srs:
         """
         """
 
 
         return 'urn:%s:def:crs:%s:%s:%s' % (
         return 'urn:%s:def:crs:%s:%s:%s' % (
-                    (self.naming_authority and self.naming_authority or "ogc"),
-                                    (self.authority or ""),
-                                    (self.version or ""),
-                                    (self.code or ""))
+            (self.naming_authority and self.naming_authority or "ogc"),
+            (self.authority or ""),
+            (self.version or ""),
+            (self.code or ""))
 
 
 axisorder_yx = frozenset([
 axisorder_yx = frozenset([
     4326,
     4326,

+ 162 - 138
scripts/r.in.wms/wms_base.py

@@ -1,5 +1,5 @@
 """!
 """!
-@brief Preparation of parameters for drivers, which download it, and managing downloaded data. 
+@brief Preparation of parameters for drivers, which download it, and managing downloaded data.
 
 
 List of classes:
 List of classes:
  - wms_base::WMSBase
  - wms_base::WMSBase
@@ -26,31 +26,32 @@ from grass.exceptions import CalledModuleError
 
 
 
 
 class WMSBase:
 class WMSBase:
+
     def __init__(self):
     def __init__(self):
         # these variables are information for destructor
         # these variables are information for destructor
         self.temp_files_to_cleanup = []
         self.temp_files_to_cleanup = []
-        
+
         self.params = {}
         self.params = {}
-        self.tile_size = {'bbox' : None}
+        self.tile_size = {'bbox': None}
 
 
         self.temp_map = None
         self.temp_map = None
         self.temp_warpmap = None
         self.temp_warpmap = None
 
 
     def __del__(self):
     def __del__(self):
-            
+
         # tries to remove temporary files, all files should be
         # tries to remove temporary files, all files should be
         # removed before, implemented just in case of unexpected
         # removed before, implemented just in case of unexpected
         # stop of module
         # stop of module
         for temp_file in self.temp_files_to_cleanup:
         for temp_file in self.temp_files_to_cleanup:
             grass.try_remove(temp_file)
             grass.try_remove(temp_file)
-        
+
     def _debug(self, fn, msg):
     def _debug(self, fn, msg):
         grass.debug("%s.%s: %s" %
         grass.debug("%s.%s: %s" %
                     (self.__class__.__name__, fn, msg))
                     (self.__class__.__name__, fn, msg))
-        
+
     def _initializeParameters(self, options, flags):
     def _initializeParameters(self, options, flags):
         self._debug("_initialize_parameters", "started")
         self._debug("_initialize_parameters", "started")
-        
+
         # initialization of module parameters (options, flags)
         # initialization of module parameters (options, flags)
         self.params['driver'] = options['driver']
         self.params['driver'] = options['driver']
         drv_info = WMSDriversInfo()
         drv_info = WMSDriversInfo()
@@ -68,46 +69,49 @@ class WMSBase:
         if self.flags['o']:
         if self.flags['o']:
             self.params['transparent'] = 'FALSE'
             self.params['transparent'] = 'FALSE'
         else:
         else:
-            self.params['transparent'] = 'TRUE'   
+            self.params['transparent'] = 'TRUE'
 
 
         for key in ['password', 'username', 'urlparams']:
         for key in ['password', 'username', 'urlparams']:
-            self.params[key] = options[key] 
+            self.params[key] = options[key]
 
 
         if (self.params ['password'] and self.params ['username'] == '') or \
         if (self.params ['password'] and self.params ['username'] == '') or \
-           (self.params ['password'] == '' and self.params ['username']):
-                grass.fatal(_("Please insert both %s and %s parameters or none of them." % ('password', 'username')))
+           (self.params['password'] == '' and self.params['username']):
+            grass.fatal(_("Please insert both %s and %s parameters or none of them." %
+                          ('password', 'username')))
 
 
         self.params['bgcolor'] = options['bgcolor'].strip()
         self.params['bgcolor'] = options['bgcolor'].strip()
 
 
         if options['format'] == "jpeg" and \
         if options['format'] == "jpeg" and \
            not 'format' in driver_props['ignored_params']:
            not 'format' in driver_props['ignored_params']:
             if not flags['o'] and \
             if not flags['o'] and \
-              'WMS' in self.params['driver']:
+                    'WMS' in self.params['driver']:
                 grass.warning(_("JPEG format does not support transparency"))
                 grass.warning(_("JPEG format does not support transparency"))
 
 
         self.params['format'] = drv_info.GetFormat(options['format'])
         self.params['format'] = drv_info.GetFormat(options['format'])
         if not self.params['format']:
         if not self.params['format']:
             self.params['format'] = self.params['format']
             self.params['format'] = self.params['format']
-        
-        #TODO: get srs from Tile Service file in OnEarth_GRASS driver 
+
+        # TODO: get srs from Tile Service file in OnEarth_GRASS driver
         self.params['srs'] = int(options['srs'])
         self.params['srs'] = int(options['srs'])
-        if self.params['srs'] <= 0 and  not 'srs' in driver_props['ignored_params']:
+        if self.params['srs'] <= 0 and not 'srs' in driver_props['ignored_params']:
             grass.fatal(_("Invalid EPSG code %d") % self.params['srs'])
             grass.fatal(_("Invalid EPSG code %d") % self.params['srs'])
 
 
-        self.params['wms_version'] = options['wms_version']  
+        self.params['wms_version'] = options['wms_version']
         if "CRS" in GetSRSParamVal(self.params['srs']) and self.params['wms_version'] == "1.1.1":
         if "CRS" in GetSRSParamVal(self.params['srs']) and self.params['wms_version'] == "1.1.1":
             self.params['wms_version'] = "1.3.0"
             self.params['wms_version'] = "1.3.0"
-            grass.warning(_("WMS version <1.3.0> will be used, because version <1.1.1> does not support <%s>projection")
-                            % GetSRSParamVal(self.params['srs']))
-        
+            grass.warning(
+                _("WMS version <1.3.0> will be used, because version <1.1.1> does not support <%s>projection") %
+                GetSRSParamVal(
+                    self.params['srs']))
+
         if self.params['wms_version'] == "1.3.0":
         if self.params['wms_version'] == "1.3.0":
             self.params['proj_name'] = "CRS"
             self.params['proj_name'] = "CRS"
         else:
         else:
             self.params['proj_name'] = "SRS"
             self.params['proj_name'] = "SRS"
 
 
         # read projection info
         # read projection info
-        self.proj_location = grass.read_command('g.proj', 
-                                                flags ='jf').rstrip('\n')
+        self.proj_location = grass.read_command('g.proj',
+                                                flags='jf').rstrip('\n')
         self.proj_location = self._modifyProj(self.proj_location)
         self.proj_location = self._modifyProj(self.proj_location)
 
 
         if self.params['srs'] in [3857, 900913]:
         if self.params['srs'] in [3857, 900913]:
@@ -116,10 +120,10 @@ class WMSBase:
             # needed to be tested on more servers
             # needed to be tested on more servers
             self.proj_srs = '+proj=merc +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +no_defs +a=6378137 +b=6378137 +nadgrids=@null +to_meter=1'
             self.proj_srs = '+proj=merc +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +no_defs +a=6378137 +b=6378137 +nadgrids=@null +to_meter=1'
         else:
         else:
-            self.proj_srs = grass.read_command('g.proj', 
-                                               flags = 'jf', 
-                                               epsg = str(GetEpsg(self.params['srs']))).rstrip('\n')
-        
+            self.proj_srs = grass.read_command('g.proj',
+                                               flags='jf',
+                                               epsg=str(GetEpsg(self.params['srs']))).rstrip('\n')
+
         self.proj_srs = self._modifyProj(self.proj_srs)
         self.proj_srs = self._modifyProj(self.proj_srs)
 
 
         if not self.proj_srs or not self.proj_location:
         if not self.proj_srs or not self.proj_location:
@@ -131,18 +135,27 @@ class WMSBase:
         maxcols = int(options['maxcols'])
         maxcols = int(options['maxcols'])
         if maxcols <= min_tile_size:
         if maxcols <= min_tile_size:
             grass.fatal(_("Maxcols must be greater than 100"))
             grass.fatal(_("Maxcols must be greater than 100"))
-        
+
         maxrows = int(options['maxrows'])
         maxrows = int(options['maxrows'])
         if maxrows <= min_tile_size:
         if maxrows <= min_tile_size:
             grass.fatal(_("Maxrows must be greater than 100"))
             grass.fatal(_("Maxrows must be greater than 100"))
-        
-        # setting optimal tile size according to maxcols and maxrows constraint and region cols and rows      
-        self.tile_size['cols'] = int(self.region['cols'] / ceil(self.region['cols'] / float(maxcols)))
-        self.tile_size['rows'] = int(self.region['rows'] / ceil(self.region['rows'] / float(maxrows)))
-        
+
+        # setting optimal tile size according to maxcols and maxrows constraint
+        # and region cols and rows
+        self.tile_size['cols'] = int(
+            self.region['cols'] /
+            ceil(
+                self.region['cols'] /
+                float(maxcols)))
+        self.tile_size['rows'] = int(
+            self.region['rows'] /
+            ceil(
+                self.region['rows'] /
+                float(maxrows)))
+
         # default format for GDAL library
         # default format for GDAL library
         self.gdal_drv_format = "GTiff"
         self.gdal_drv_format = "GTiff"
-        
+
         self._debug("_initialize_parameters", "finished")
         self._debug("_initialize_parameters", "finished")
 
 
     def _modifyProj(self, proj):
     def _modifyProj(self, proj):
@@ -160,34 +173,34 @@ class WMSBase:
         not_relevant_params = []
         not_relevant_params = []
         for i_param in driver_props['ignored_params']:
         for i_param in driver_props['ignored_params']:
 
 
-            if options.has_key(i_param) and \
+            if i_param in options and \
                options[i_param] and \
                options[i_param] and \
-               i_param not in ['srs', 'wms_version', 'format']: # params with default value
-                not_relevant_params.append('<' + i_param  + '>')
+               i_param not in ['srs', 'wms_version', 'format']:  # params with default value
+                not_relevant_params.append('<' + i_param + '>')
 
 
         if len(not_relevant_params) > 0:
         if len(not_relevant_params) > 0:
             grass.warning(_("These parameter are ignored: %s\n\
             grass.warning(_("These parameter are ignored: %s\n\
-                             %s driver does not support the parameters." %\
+                             %s driver does not support the parameters." %
                             (','.join(not_relevant_params), options['driver'])))
                             (','.join(not_relevant_params), options['driver'])))
 
 
         not_relevant_flags = []
         not_relevant_flags = []
         for i_flag in driver_props['ignored_flags']:
         for i_flag in driver_props['ignored_flags']:
 
 
             if flags[i_flag]:
             if flags[i_flag]:
-                not_relevant_flags.append('<' + i_flag  + '>')
+                not_relevant_flags.append('<' + i_flag + '>')
 
 
         if len(not_relevant_flags) > 0:
         if len(not_relevant_flags) > 0:
             grass.warning(_("These flags are ignored: %s\n\
             grass.warning(_("These flags are ignored: %s\n\
-                             %s driver does not support the flags." %\
+                             %s driver does not support the flags." %
                             (','.join(not_relevant_flags), options['driver'])))
                             (','.join(not_relevant_flags), options['driver'])))
 
 
     def GetMap(self, options, flags):
     def GetMap(self, options, flags):
         """!Download data from WMS server."""
         """!Download data from WMS server."""
 
 
-        self._initializeParameters(options, flags)  
+        self._initializeParameters(options, flags)
+
+        self.bbox = self._computeBbox()
 
 
-        self.bbox     = self._computeBbox()
-        
         self.temp_map = self._download()
         self.temp_map = self._download()
 
 
         if not self.temp_map:
         if not self.temp_map:
@@ -196,8 +209,8 @@ class WMSBase:
         self._reprojectMap()
         self._reprojectMap()
 
 
         return self.temp_warpmap
         return self.temp_warpmap
-    
-    def _fetchCapabilities(self, options): 
+
+    def _fetchCapabilities(self, options):
         """!Download capabilities from WMS server
         """!Download capabilities from WMS server
         """
         """
         cap_url = options['url'].strip()
         cap_url = options['url'].strip()
@@ -212,46 +225,48 @@ class WMSBase:
         elif 'OnEarth' in options['driver']:
         elif 'OnEarth' in options['driver']:
             cap_url += "REQUEST=GetTileService"
             cap_url += "REQUEST=GetTileService"
         else:
         else:
-            cap_url += "SERVICE=WMS&REQUEST=GetCapabilities&VERSION=" + options['wms_version'] 
+            cap_url += "SERVICE=WMS&REQUEST=GetCapabilities&VERSION=" + options['wms_version']
 
 
         if options['urlparams']:
         if options['urlparams']:
             cap_url += "&" + options['urlparams']
             cap_url += "&" + options['urlparams']
-            
+
         grass.debug('Fetching capabilities file.\n%s' % cap_url)
         grass.debug('Fetching capabilities file.\n%s' % cap_url)
 
 
         try:
         try:
             cap = self._fetchDataFromServer(cap_url, options['username'], options['password'])
             cap = self._fetchDataFromServer(cap_url, options['username'], options['password'])
         except (IOError, HTTPException) as e:
         except (IOError, HTTPException) as e:
-            if urllib2.HTTPError == type(e) and e.code == 401:
-                grass.fatal(_("Authorization failed to <%s> when fetching capabilities") % options['url'])
+            if isinstance(e, urllib2.HTTPError) and e.code == 401:
+                grass.fatal(
+                    _("Authorization failed to <%s> when fetching capabilities") %
+                    options['url'])
             else:
             else:
                 msg = _("Unable to fetch capabilities from <%s>: %s") % (options['url'], e)
                 msg = _("Unable to fetch capabilities from <%s>: %s") % (options['url'], e)
-                
+
                 if hasattr(e, 'reason'):
                 if hasattr(e, 'reason'):
                     msg += _("\nReason: ") + e.reason
                     msg += _("\nReason: ") + e.reason
-                
+
                 grass.fatal(msg)
                 grass.fatal(msg)
-        
+
         grass.debug('Fetching capabilities OK')
         grass.debug('Fetching capabilities OK')
         return cap
         return cap
 
 
-    def _fetchDataFromServer(self, url, username = None, password = None):
+    def _fetchDataFromServer(self, url, username=None, password=None):
         """!Fetch data from server
         """!Fetch data from server
-        """      
+        """
         request = urllib2.Request(url)
         request = urllib2.Request(url)
         if username and password:
         if username and password:
-                    base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
-                    request.add_header("Authorization", "Basic %s" % base64string)
-        
+            base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
+            request.add_header("Authorization", "Basic %s" % base64string)
+
         try:
         try:
             return urllib2.urlopen(request)
             return urllib2.urlopen(request)
         except ValueError as error:
         except ValueError as error:
             grass.fatal("%s" % error)
             grass.fatal("%s" % error)
 
 
-    def GetCapabilities(self, options): 
+    def GetCapabilities(self, options):
         """!Get capabilities from WMS server
         """!Get capabilities from WMS server
         """
         """
-        cap  = self._fetchCapabilities(options)
+        cap = self._fetchCapabilities(options)
         capfile_output = options['capfile_output'].strip()
         capfile_output = options['capfile_output'].strip()
 
 
         # save to file
         # save to file
@@ -261,61 +276,61 @@ class WMSBase:
                 temp.write(cap.read())
                 temp.write(cap.read())
                 temp.close()
                 temp.close()
                 return
                 return
-            except IOError as error: 
+            except IOError as error:
                 grass.fatal(_("Unabble to open file '%s'.\n%s\n" % (cap_file, error)))
                 grass.fatal(_("Unabble to open file '%s'.\n%s\n" % (cap_file, error)))
-        
+
         # print to output
         # print to output
         cap_lines = cap.readlines()
         cap_lines = cap.readlines()
-        for line in cap_lines: 
+        for line in cap_lines:
             print line.rstrip()
             print line.rstrip()
-        
+
     def _computeBbox(self):
     def _computeBbox(self):
         """!Get region extent for WMS query (bbox)
         """!Get region extent for WMS query (bbox)
         """
         """
         self._debug("_computeBbox", "started")
         self._debug("_computeBbox", "started")
-        
-        bbox_region_items = {'maxy' : 'n', 'miny' : 's', 'maxx' : 'e', 'minx' : 'w'}  
+
+        bbox_region_items = {'maxy': 'n', 'miny': 's', 'maxx': 'e', 'minx': 'w'}
         bbox = {}
         bbox = {}
 
 
-        if self.proj_srs == self.proj_location: # TODO: do it better
+        if self.proj_srs == self.proj_location:  # TODO: do it better
             for bbox_item, region_item in bbox_region_items.iteritems():
             for bbox_item, region_item in bbox_region_items.iteritems():
                 bbox[bbox_item] = self.region[region_item]
                 bbox[bbox_item] = self.region[region_item]
-        
+
         # if location projection and wms query projection are
         # if location projection and wms query projection are
         # different, corner points of region are transformed into wms
         # different, corner points of region are transformed into wms
         # projection and then bbox is created from extreme coordinates
         # projection and then bbox is created from extreme coordinates
         # of the transformed points
         # of the transformed points
         else:
         else:
-            for bbox_item, region_item  in bbox_region_items.iteritems():
+            for bbox_item, region_item in bbox_region_items.iteritems():
                 bbox[bbox_item] = None
                 bbox[bbox_item] = None
 
 
             temp_region = self._tempfile()
             temp_region = self._tempfile()
-            
+
             try:
             try:
                 temp_region_opened = open(temp_region, 'w')
                 temp_region_opened = open(temp_region, 'w')
-                temp_region_opened.write("%f %f\n%f %f\n%f %f\n%f %f\n"  %\
-                                       (self.region['e'], self.region['n'],\
-                                        self.region['w'], self.region['n'],\
-                                        self.region['w'], self.region['s'],\
-                                        self.region['e'], self.region['s'] ))
+                temp_region_opened.write("%f %f\n%f %f\n%f %f\n%f %f\n" %
+                                         (self.region['e'], self.region['n'],
+                                          self.region['w'], self.region['n'],
+                                          self.region['w'], self.region['s'],
+                                          self.region['e'], self.region['s']))
             except IOError:
             except IOError:
-                 grass.fatal(_("Unable to write data into tempfile"))
-            finally:           
-                temp_region_opened.close()            
-
-            points = grass.read_command('m.proj', flags = 'd',
-                                        proj_out = self.proj_srs,
-                                        proj_in = self.proj_location,
-                                        input = temp_region,
-                                        quiet = True) # TODO: stdin
+                grass.fatal(_("Unable to write data into tempfile"))
+            finally:
+                temp_region_opened.close()
+
+            points = grass.read_command('m.proj', flags='d',
+                                        proj_out=self.proj_srs,
+                                        proj_in=self.proj_location,
+                                        input=temp_region,
+                                        quiet=True)  # TODO: stdin
             grass.try_remove(temp_region)
             grass.try_remove(temp_region)
             if not points:
             if not points:
                 grass.fatal(_("Unable to determine region, %s failed") % 'm.proj')
                 grass.fatal(_("Unable to determine region, %s failed") % 'm.proj')
-            
+
             points = points.splitlines()
             points = points.splitlines()
             if len(points) != 4:
             if len(points) != 4:
                 grass.fatal(_("Region definition: 4 points required"))
                 grass.fatal(_("Region definition: 4 points required"))
-            
+
             for point in points:
             for point in points:
                 try:
                 try:
                     point = map(float, point.split("|"))
                     point = map(float, point.split("|"))
@@ -327,33 +342,33 @@ class WMSBase:
                     bbox['maxx'] = point[0]
                     bbox['maxx'] = point[0]
                     bbox['minx'] = point[0]
                     bbox['minx'] = point[0]
                     continue
                     continue
-                
-                if   bbox['maxy'] < point[1]:
+
+                if bbox['maxy'] < point[1]:
                     bbox['maxy'] = point[1]
                     bbox['maxy'] = point[1]
                 elif bbox['miny'] > point[1]:
                 elif bbox['miny'] > point[1]:
                     bbox['miny'] = point[1]
                     bbox['miny'] = point[1]
-                
-                if   bbox['maxx'] < point[0]:
+
+                if bbox['maxx'] < point[0]:
                     bbox['maxx'] = point[0]
                     bbox['maxx'] = point[0]
                 elif bbox['minx'] > point[0]:
                 elif bbox['minx'] > point[0]:
-                    bbox['minx'] = point[0]  
-        
+                    bbox['minx'] = point[0]
+
         self._debug("_computeBbox", "finished -> %s" % bbox)
         self._debug("_computeBbox", "finished -> %s" % bbox)
 
 
         # Ordering of coordinates axis of geographic coordinate
         # Ordering of coordinates axis of geographic coordinate
-        # systems in WMS 1.3.0 is flipped. If  self.tile_size['flip_coords'] is 
+        # systems in WMS 1.3.0 is flipped. If  self.tile_size['flip_coords'] is
         # True, coords in bbox need to be flipped in WMS query.
         # True, coords in bbox need to be flipped in WMS query.
 
 
         return bbox
         return bbox
 
 
-    def _reprojectMap(self): 
+    def _reprojectMap(self):
         """!Reproject data  using gdalwarp if needed
         """!Reproject data  using gdalwarp if needed
         """
         """
         # reprojection of raster
         # reprojection of raster
-        if self.proj_srs != self.proj_location: # TODO: do it better
+        if self.proj_srs != self.proj_location:  # TODO: do it better
             grass.message(_("Reprojecting raster..."))
             grass.message(_("Reprojecting raster..."))
             self.temp_warpmap = grass.tempfile()
             self.temp_warpmap = grass.tempfile()
-            
+
             if int(os.getenv('GRASS_VERBOSE', '2')) <= 2:
             if int(os.getenv('GRASS_VERBOSE', '2')) <= 2:
                 nuldev = file(os.devnull, 'w+')
                 nuldev = file(os.devnull, 'w+')
             else:
             else:
@@ -365,7 +380,7 @@ class WMSBase:
                 gdal_method = "bilinear"
                 gdal_method = "bilinear"
             else:
             else:
                 gdal_method = self.params['method']
                 gdal_method = self.params['method']
-            
+
             #"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs"
             #"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs"
             # RGB rasters - alpha layer is added for cropping edges of projected raster
             # RGB rasters - alpha layer is added for cropping edges of projected raster
             try:
             try:
@@ -374,21 +389,21 @@ class WMSBase:
                                       '-s_srs', '%s' % self.proj_srs,
                                       '-s_srs', '%s' % self.proj_srs,
                                       '-t_srs', '%s' % self.proj_location,
                                       '-t_srs', '%s' % self.proj_location,
                                       '-r', gdal_method, '-dstalpha',
                                       '-r', gdal_method, '-dstalpha',
-                                      self.temp_map, self.temp_warpmap], stdout = nuldev)
+                                      self.temp_map, self.temp_warpmap], stdout=nuldev)
                 # RGBA rasters
                 # RGBA rasters
                 else:
                 else:
                     ps = grass.Popen(['gdalwarp',
                     ps = grass.Popen(['gdalwarp',
                                       '-s_srs', '%s' % self.proj_srs,
                                       '-s_srs', '%s' % self.proj_srs,
                                       '-t_srs', '%s' % self.proj_location,
                                       '-t_srs', '%s' % self.proj_location,
                                       '-r', gdal_method,
                                       '-r', gdal_method,
-                                      self.temp_map, self.temp_warpmap], stdout = nuldev)
+                                      self.temp_map, self.temp_warpmap], stdout=nuldev)
                 ps.wait()
                 ps.wait()
             except OSError as e:
             except OSError as e:
                 grass.fatal('%s \nThis can be caused by missing %s utility. ' % (e, 'gdalwarp'))
                 grass.fatal('%s \nThis can be caused by missing %s utility. ' % (e, 'gdalwarp'))
-            
+
             if nuldev:
             if nuldev:
                 nuldev.close()
                 nuldev.close()
-            
+
             if ps.returncode != 0:
             if ps.returncode != 0:
                 grass.fatal(_('%s failed') % 'gdalwarp')
                 grass.fatal(_('%s failed') % 'gdalwarp')
             grass.try_remove(self.temp_map)
             grass.try_remove(self.temp_map)
@@ -398,26 +413,28 @@ class WMSBase:
             self.temp_files_to_cleanup.remove(self.temp_map)
             self.temp_files_to_cleanup.remove(self.temp_map)
 
 
         return self.temp_warpmap
         return self.temp_warpmap
-        
+
     def _tempfile(self):
     def _tempfile(self):
-        """!Create temp_file and append list self.temp_files_to_cleanup 
-            with path of file 
-     
+        """!Create temp_file and append list self.temp_files_to_cleanup
+            with path of file
+
         @return string path to temp_file
         @return string path to temp_file
         """
         """
         temp_file = grass.tempfile()
         temp_file = grass.tempfile()
         if temp_file is None:
         if temp_file is None:
             grass.fatal(_("Unable to create temporary files"))
             grass.fatal(_("Unable to create temporary files"))
-        
+
         # list of created tempfiles for destructor
         # list of created tempfiles for destructor
         self.temp_files_to_cleanup.append(temp_file)
         self.temp_files_to_cleanup.append(temp_file)
-        
+
         return temp_file
         return temp_file
 
 
+
 class GRASSImporter:
 class GRASSImporter:
+
     def __init__(self, opt_output):
     def __init__(self, opt_output):
 
 
-        self.cleanup_mask   = False
+        self.cleanup_mask = False
         self.cleanup_layers = False
         self.cleanup_layers = False
 
 
         # output map name
         # output map name
@@ -427,13 +444,13 @@ class GRASSImporter:
         # into raster named:self.opt_output + this suffix)
         # into raster named:self.opt_output + this suffix)
         self.original_mask_suffix = "_temp_MASK"
         self.original_mask_suffix = "_temp_MASK"
 
 
-        # check names of temporary rasters, which module may create 
+        # check names of temporary rasters, which module may create
         maps = []
         maps = []
-        for suffix in ('.red', '.green', '.blue', '.alpha', self.original_mask_suffix ):
+        for suffix in ('.red', '.green', '.blue', '.alpha', self.original_mask_suffix):
             rast = self.opt_output + suffix
             rast = self.opt_output + suffix
-            if grass.find_file(rast, element = 'cell', mapset = '.')['file']:
+            if grass.find_file(rast, element='cell', mapset='.')['file']:
                 maps.append(rast)
                 maps.append(rast)
-        
+
         if len(maps) != 0:
         if len(maps) != 0:
             grass.fatal(_("Please change output name, or change names of these rasters: %s, "
             grass.fatal(_("Please change output name, or change names of these rasters: %s, "
                           "module needs to create this temporary maps during execution.") % ",".join(maps))
                           "module needs to create this temporary maps during execution.") % ",".join(maps))
@@ -447,8 +464,9 @@ class GRASSImporter:
             except CalledModuleError:
             except CalledModuleError:
                 grass.fatal(_('%s failed') % 'r.mask')
                 grass.fatal(_('%s failed') % 'r.mask')
 
 
-            # restore original mask, if exists 
-            if grass.find_file(self.opt_output + self.original_mask_suffix, element = 'cell', mapset = '.' )['name']:
+            # restore original mask, if exists
+            if grass.find_file(self.opt_output + self.original_mask_suffix,
+                               element='cell', mapset='.')['name']:
                 try:
                 try:
                     mask_copy = self.opt_output + self.original_mask_suffix
                     mask_copy = self.opt_output + self.original_mask_suffix
                     grass.run_command('g.copy', quiet=True,
                     grass.run_command('g.copy', quiet=True,
@@ -457,25 +475,25 @@ class GRASSImporter:
                     grass.fatal(_('%s failed') % 'g.copy')
                     grass.fatal(_('%s failed') % 'g.copy')
 
 
         # remove temporary created rasters
         # remove temporary created rasters
-        if self.cleanup_layers: 
+        if self.cleanup_layers:
             maps = []
             maps = []
             for suffix in ('.red', '.green', '.blue', '.alpha', self.original_mask_suffix):
             for suffix in ('.red', '.green', '.blue', '.alpha', self.original_mask_suffix):
                 rast = self.opt_output + suffix
                 rast = self.opt_output + suffix
-                if grass.find_file(rast, element = 'cell', mapset = '.')['file']:
+                if grass.find_file(rast, element='cell', mapset='.')['file']:
                     maps.append(rast)
                     maps.append(rast)
-            
+
             if maps:
             if maps:
                 grass.run_command('g.remove',
                 grass.run_command('g.remove',
-                                  quiet = True,
-                                  flags = 'fb',
-                                  type = 'raster',
-                                  name = ','.join(maps))
-        
-        # delete environmental variable which overrides region 
+                                  quiet=True,
+                                  flags='fb',
+                                  type='raster',
+                                  name=','.join(maps))
+
+        # delete environmental variable which overrides region
         if 'GRASS_REGION' in os.environ.keys():
         if 'GRASS_REGION' in os.environ.keys():
             os.environ.pop('GRASS_REGION')
             os.environ.pop('GRASS_REGION')
 
 
-    def ImportMapIntoGRASS(self, raster): 
+    def ImportMapIntoGRASS(self, raster):
         """!Import raster into GRASS.
         """!Import raster into GRASS.
         """
         """
         # importing temp_map into GRASS
         # importing temp_map into GRASS
@@ -489,20 +507,20 @@ class GRASSImporter:
         # information for destructor to cleanup temp_layers, created
         # information for destructor to cleanup temp_layers, created
         # with r.in.gdal
         # with r.in.gdal
         self.cleanup_layers = True
         self.cleanup_layers = True
-        
+
         # setting region for full extend of imported raster
         # setting region for full extend of imported raster
-        if grass.find_file(self.opt_output + '.red', element = 'cell', mapset = '.')['file']:
+        if grass.find_file(self.opt_output + '.red', element='cell', mapset='.')['file']:
             region_map = self.opt_output + '.red'
             region_map = self.opt_output + '.red'
         else:
         else:
             region_map = self.opt_output
             region_map = self.opt_output
-        os.environ['GRASS_REGION'] = grass.region_env(rast = region_map)
-          
+        os.environ['GRASS_REGION'] = grass.region_env(rast=region_map)
+
         # mask created from alpha layer, which describes real extend
         # mask created from alpha layer, which describes real extend
         # of warped layer (may not be a rectangle), also mask contains
         # of warped layer (may not be a rectangle), also mask contains
         # transparent parts of raster
         # transparent parts of raster
-        if grass.find_file( self.opt_output + '.alpha', element = 'cell', mapset = '.' )['name']:
+        if grass.find_file(self.opt_output + '.alpha', element='cell', mapset='.')['name']:
             # saving current mask (if exists) into temp raster
             # saving current mask (if exists) into temp raster
-            if grass.find_file('MASK', element = 'cell', mapset = '.' )['name']:
+            if grass.find_file('MASK', element='cell', mapset='.')['name']:
                 try:
                 try:
                     mask_copy = self.opt_output + self.original_mask_suffix
                     mask_copy = self.opt_output + self.original_mask_suffix
                     grass.run_command('g.copy', quiet=True,
                     grass.run_command('g.copy', quiet=True,
@@ -521,8 +539,8 @@ class GRASSImporter:
             except CalledModuleError:
             except CalledModuleError:
                 grass.fatal(_('%s failed') % 'r.mask')
                 grass.fatal(_('%s failed') % 'r.mask')
 
 
-        #TODO one band + alpha band?
-        if grass.find_file(self.opt_output + '.red', element = 'cell', mapset = '.')['file']:
+        # TODO one band + alpha band?
+        if grass.find_file(self.opt_output + '.red', element='cell', mapset='.')['file']:
             try:
             try:
                 grass.run_command('r.composite',
                 grass.run_command('r.composite',
                                   quiet=True, overwrite=True,
                                   quiet=True, overwrite=True,
@@ -535,7 +553,9 @@ class GRASSImporter:
 
 
         grass.message(_('<%s> created.') % self.opt_output)
         grass.message(_('<%s> created.') % self.opt_output)
 
 
+
 class WMSDriversInfo:
 class WMSDriversInfo:
+
     def __init__(self):
     def __init__(self):
         """!Provides information about driver parameters.
         """!Provides information about driver parameters.
         """
         """
@@ -544,11 +564,16 @@ class WMSDriversInfo:
         self.f_labels = ["geotiff", "tiff", "png", "jpeg", "gif", "png8"]
         self.f_labels = ["geotiff", "tiff", "png", "jpeg", "gif", "png8"]
 
 
         # form for request
         # form for request
-        self.formats = ["image/geotiff", "image/tiff", "image/png", "image/jpeg", "image/gif", "image/png8"]
+        self.formats = [
+            "image/geotiff",
+            "image/tiff",
+            "image/png",
+            "image/jpeg",
+            "image/gif",
+            "image/png8"]
 
 
         self.srs = ("epsg", "crs")
         self.srs = ("epsg", "crs")
 
 
-
     def GetDrvProperties(self, driver):
     def GetDrvProperties(self, driver):
         """!Get information about driver parameters.
         """!Get information about driver parameters.
         """
         """
@@ -561,12 +586,11 @@ class WMSDriversInfo:
         if 'OnEarth' in driver:
         if 'OnEarth' in driver:
             return self._OnEarthProperties()
             return self._OnEarthProperties()
 
 
-
     def _OnEarthProperties(self):
     def _OnEarthProperties(self):
 
 
         props = {}
         props = {}
         props['ignored_flags'] = ['o']
         props['ignored_flags'] = ['o']
-        props['ignored_params'] = ['bgcolor', 'styles', 'capfile_output', 
+        props['ignored_params'] = ['bgcolor', 'styles', 'capfile_output',
                                    'format', 'srs', 'wms_version']
                                    'format', 'srs', 'wms_version']
         props['req_multiple_layers'] = False
         props['req_multiple_layers'] = False
 
 
@@ -595,7 +619,7 @@ class WMSDriversInfo:
         props = {}
         props = {}
         props['ignored_flags'] = []
         props['ignored_flags'] = []
         props['ignored_params'] = ['urlparams', 'bgcolor', 'capfile', 'capfile_output',
         props['ignored_params'] = ['urlparams', 'bgcolor', 'capfile', 'capfile_output',
-                                    'username', 'password']
+                                   'username', 'password']
         props['req_multiple_layers'] = True
         props['req_multiple_layers'] = True
 
 
         return props
         return props
@@ -622,8 +646,7 @@ class WMSDriversInfo:
         return self.srs
         return self.srs
 
 
 
 
-
-#TODO move to utils?
+# TODO move to utils?
 def GetSRSParamVal(srs):
 def GetSRSParamVal(srs):
     """!Decides whether to use CRS or EPSG prefix according to srs number.
     """!Decides whether to use CRS or EPSG prefix according to srs number.
     """
     """
@@ -633,11 +656,12 @@ def GetSRSParamVal(srs):
     else:
     else:
         return "EPSG:%d" % srs
         return "EPSG:%d" % srs
 
 
+
 def GetEpsg(srs):
 def GetEpsg(srs):
     """
     """
-     @return EPSG number 
+     @return EPSG number
              If srs is CRS number, return EPSG number which corresponds to CRS number.
              If srs is CRS number, return EPSG number which corresponds to CRS number.
-    """    
+    """
     if srs == 84:
     if srs == 84:
         return 4326
         return 4326
     if srs == 83:
     if srs == 83:

+ 88 - 76
scripts/r.in.wms/wms_cap_parsers.py

@@ -18,32 +18,36 @@ This program is free software under the GNU General Public License
 """
 """
 try:
 try:
     from xml.etree.ElementTree import ParseError
     from xml.etree.ElementTree import ParseError
-except ImportError: # < Python 2.7
+except ImportError:  # < Python 2.7
     from xml.parsers.expat import ExpatError as ParseError
     from xml.parsers.expat import ExpatError as ParseError
 
 
 import xml.etree.ElementTree as etree
 import xml.etree.ElementTree as etree
-import grass.script as grass 
+import grass.script as grass
+
 
 
 class BaseCapabilitiesTree(etree.ElementTree):
 class BaseCapabilitiesTree(etree.ElementTree):
+
     def __init__(self, cap_file):
     def __init__(self, cap_file):
         """!Initialize xml.etree.ElementTree
         """!Initialize xml.etree.ElementTree
         """
         """
         try:
         try:
-            etree.ElementTree.__init__(self, file = cap_file)
+            etree.ElementTree.__init__(self, file=cap_file)
         except ParseError:
         except ParseError:
             raise ParseError(_("Unable to parse XML file"))
             raise ParseError(_("Unable to parse XML file"))
         except IOError as error:
         except IOError as error:
             raise ParseError(_("Unable to open XML file '%s'.\n%s\n" % (cap_file, error)))
             raise ParseError(_("Unable to open XML file '%s'.\n%s\n" % (cap_file, error)))
 
 
         if self.getroot() is None:
         if self.getroot() is None:
-            raise ParseError(_("Root node was not found.")) 
-        
+            raise ParseError(_("Root node was not found."))
+
+
 class WMSXMLNsHandler:
 class WMSXMLNsHandler:
+
     def __init__(self, caps):
     def __init__(self, caps):
         """!Handle XML namespaces according to WMS version of capabilities.
         """!Handle XML namespaces according to WMS version of capabilities.
         """
         """
         self.namespace = "{http://www.opengis.net/wms}"
         self.namespace = "{http://www.opengis.net/wms}"
-        
+
         if caps.getroot().find("Service") is not None:
         if caps.getroot().find("Service") is not None:
             self.use_ns = False
             self.use_ns = False
         elif caps.getroot().find(self.namespace + "Service") is not None:
         elif caps.getroot().find(self.namespace + "Service") is not None:
@@ -51,7 +55,7 @@ class WMSXMLNsHandler:
         else:
         else:
             raise ParseError(_("Unable to parse capabilities file.\n\
             raise ParseError(_("Unable to parse capabilities file.\n\
                                 Tag <%s> was not found.") % "Service")
                                 Tag <%s> was not found.") % "Service")
-    
+
     def Ns(self, tag_name):
     def Ns(self, tag_name):
         """!Add namespace to tag_name according to version
         """!Add namespace to tag_name according to version
         """
         """
@@ -59,30 +63,32 @@ class WMSXMLNsHandler:
             tag_name = self.namespace + tag_name
             tag_name = self.namespace + tag_name
         return tag_name
         return tag_name
 
 
+
 class WMSCapabilitiesTree(BaseCapabilitiesTree):
 class WMSCapabilitiesTree(BaseCapabilitiesTree):
-    def __init__(self, cap_file, force_version = None):
+
+    def __init__(self, cap_file, force_version=None):
         """!Parses WMS capabilities file.
         """!Parses WMS capabilities file.
             If the capabilities file cannot be parsed if it raises xml.etree.ElementTree.ParseError.
             If the capabilities file cannot be parsed if it raises xml.etree.ElementTree.ParseError.
 
 
-        The class manges inheritance in 'Layer' elements. Inherited elements 
+        The class manges inheritance in 'Layer' elements. Inherited elements
         are added to 'Layer' element.
         are added to 'Layer' element.
-        The class also removes elements which are in invalid form and are needed 
+        The class also removes elements which are in invalid form and are needed
         by wxGUI capabilities dialog.
         by wxGUI capabilities dialog.
 
 
-        @param cap_file - capabilities file        
+        @param cap_file - capabilities file
         @param force_version - force capabilities file version (1.1.1, 1.3.0)
         @param force_version - force capabilities file version (1.1.1, 1.3.0)
         """
         """
         BaseCapabilitiesTree.__init__(self, cap_file)
         BaseCapabilitiesTree.__init__(self, cap_file)
         self.xml_ns = WMSXMLNsHandler(self)
         self.xml_ns = WMSXMLNsHandler(self)
 
 
         grass.debug('Checking WMS capabilities tree.', 4)
         grass.debug('Checking WMS capabilities tree.', 4)
-        
+
         if not "version" in self.getroot().attrib:
         if not "version" in self.getroot().attrib:
             raise ParseError(_("Missing version attribute root node "
             raise ParseError(_("Missing version attribute root node "
-                                "in Capabilities XML file"))
+                               "in Capabilities XML file"))
         else:
         else:
             wms_version = self.getroot().attrib["version"]
             wms_version = self.getroot().attrib["version"]
-        
+
         if wms_version == "1.3.0":
         if wms_version == "1.3.0":
             self.proj_tag = "CRS"
             self.proj_tag = "CRS"
         else:
         else:
@@ -102,54 +108,54 @@ class WMSCapabilitiesTree(BaseCapabilitiesTree):
 
 
     def _checkFormats(self, capability):
     def _checkFormats(self, capability):
         """!Check if format element is defined.
         """!Check if format element is defined.
-        """        
+        """
         request = self._find(capability, "Request")
         request = self._find(capability, "Request")
         get_map = self._find(request, "GetMap")
         get_map = self._find(request, "GetMap")
         formats = self._findall(get_map, "Format")
         formats = self._findall(get_map, "Format")
- 
-    def _checkLayerTree(self, parent_layer, first = True):
+
+    def _checkLayerTree(self, parent_layer, first=True):
         """!Recursively check layer tree and manage inheritance in the tree
         """!Recursively check layer tree and manage inheritance in the tree
         """
         """
         if first:
         if first:
             self._initLayer(parent_layer, None)
             self._initLayer(parent_layer, None)
-        
+
         layers = parent_layer.findall((self.xml_ns.Ns("Layer")))
         layers = parent_layer.findall((self.xml_ns.Ns("Layer")))
-        
+
         for l in layers:
         for l in layers:
             self._initLayer(l, parent_layer)
             self._initLayer(l, parent_layer)
             self._checkLayerTree(l, False)
             self._checkLayerTree(l, False)
-        
+
     def _initLayer(self, layer, parent_layer):
     def _initLayer(self, layer, parent_layer):
         """Inherit elements from parent layer
         """Inherit elements from parent layer
 
 
         @param layer - <Layer> element which inherits
         @param layer - <Layer> element which inherits
-        @param parent_layer - <Layer> element which is inherited from 
+        @param parent_layer - <Layer> element which is inherited from
         """
         """
         if parent_layer is not None:
         if parent_layer is not None:
-            replaced_elements = [ ["EX_GeographicBoundingBox", "replace"],
-                                  ["Attribution", "replace"],
-                                  ["MinScaleDenominator", "replace"],
-                                  ["MaxScaleDenominator", "replace"],
-                                  ["AuthorityURL", "add"]]
-            
+            replaced_elements = [["EX_GeographicBoundingBox", "replace"],
+                                 ["Attribution", "replace"],
+                                 ["MinScaleDenominator", "replace"],
+                                 ["MaxScaleDenominator", "replace"],
+                                 ["AuthorityURL", "add"]]
+
             for element in replaced_elements:
             for element in replaced_elements:
                 elems = layer.findall(self.xml_ns.Ns(element[0]))
                 elems = layer.findall(self.xml_ns.Ns(element[0]))
 
 
                 if len(elems) != 0 or element[1] == "add":
                 if len(elems) != 0 or element[1] == "add":
                     for e in parent_layer.findall(self.xml_ns.Ns(element[0])):
                     for e in parent_layer.findall(self.xml_ns.Ns(element[0])):
                         layer.append(e)
                         layer.append(e)
-            
+
             inh_arguments = ["queryable", "cascaded", "opaque",
             inh_arguments = ["queryable", "cascaded", "opaque",
                              "noSubsets", "fixedWidth", "fixedHeight"]
                              "noSubsets", "fixedWidth", "fixedHeight"]
-            
+
             for attr in parent_layer.attrib:
             for attr in parent_layer.attrib:
                 if attr not in layer.attrib and attr in inh_arguments:
                 if attr not in layer.attrib and attr in inh_arguments:
                     layer.attrib[attr] = parent_layer.attrib[attr]
                     layer.attrib[attr] = parent_layer.attrib[attr]
-            
+
             self._inhNotSame(self.proj_tag, "element_content", layer, parent_layer)
             self._inhNotSame(self.proj_tag, "element_content", layer, parent_layer)
             self._inhNotSame("BoundingBox", "attribute", layer, parent_layer, self.proj_tag)
             self._inhNotSame("BoundingBox", "attribute", layer, parent_layer, self.proj_tag)
 
 
-            # remove invalid Styles 
+            # remove invalid Styles
             styles = layer.findall(self.xml_ns.Ns('Style'))
             styles = layer.findall(self.xml_ns.Ns('Style'))
             for s in styles:
             for s in styles:
                 s_name = s.find(self.xml_ns.Ns('Name'))
                 s_name = s.find(self.xml_ns.Ns('Name'))
@@ -160,7 +166,7 @@ class WMSCapabilitiesTree(BaseCapabilitiesTree):
             self._inhNotSame("Style", "child_element_content", layer, parent_layer, "Name")
             self._inhNotSame("Style", "child_element_content", layer, parent_layer, "Name")
             self._inhNotSame("Dimension", "attribute", layer, parent_layer, "name")
             self._inhNotSame("Dimension", "attribute", layer, parent_layer, "name")
 
 
-    def _inhNotSame(self, element_name, cmp_type, layer, parent_layer, add_arg = None):
+    def _inhNotSame(self, element_name, cmp_type, layer, parent_layer, add_arg=None):
         """Inherit elements which have unique values.
         """Inherit elements which have unique values.
 
 
         @param element_name - name of inherited element
         @param element_name - name of inherited element
@@ -168,7 +174,7 @@ class WMSCapabilitiesTree(BaseCapabilitiesTree):
         @param cmp_type - 'child_element_content' - compared value is text of a child of the <Layer> element
         @param cmp_type - 'child_element_content' - compared value is text of a child of the <Layer> element
         @param cmp_type - 'attribute' - compared value is text of the <Layer> element attribute
         @param cmp_type - 'attribute' - compared value is text of the <Layer> element attribute
         @param layer - <Layer> element which inherits
         @param layer - <Layer> element which inherits
-        @param parent_layer - <Layer> element which is inherited from 
+        @param parent_layer - <Layer> element which is inherited from
         @param add_arg - name of child element or attribute
         @param add_arg - name of child element or attribute
         """
         """
         elem = layer.findall(self.xml_ns.Ns(element_name))
         elem = layer.findall(self.xml_ns.Ns(element_name))
@@ -176,50 +182,50 @@ class WMSCapabilitiesTree(BaseCapabilitiesTree):
         parent_elems = []
         parent_elems = []
         if parent_layer is not None:
         if parent_layer is not None:
             parent_elems = parent_layer.findall(self.xml_ns.Ns(element_name))
             parent_elems = parent_layer.findall(self.xml_ns.Ns(element_name))
-        
+
         for par_elem in parent_elems:
         for par_elem in parent_elems:
             parent_cmp_text = None
             parent_cmp_text = None
             if cmp_type == "attribute":
             if cmp_type == "attribute":
                 if add_arg in par_elem.attrib:
                 if add_arg in par_elem.attrib:
-                    parent_cmp_text = par_elem.attrib[add_arg];
+                    parent_cmp_text = par_elem.attrib[add_arg]
 
 
             elif cmp_type == "element_content":
             elif cmp_type == "element_content":
                 parent_cmp_text = par_elem.text
                 parent_cmp_text = par_elem.text
-                
+
             elif cmp_type == "child_element_content":
             elif cmp_type == "child_element_content":
                 parent_cmp = par_elem.find(self.xml_ns.Ns(add_arg))
                 parent_cmp = par_elem.find(self.xml_ns.Ns(add_arg))
                 if parent_cmp is not None:
                 if parent_cmp is not None:
                     parent_cmp_text = parent_cmp.text
                     parent_cmp_text = parent_cmp.text
-            
+
             if parent_cmp_text is None:
             if parent_cmp_text is None:
                 continue
                 continue
-            
+
             is_there = False
             is_there = False
             for elem in elem:
             for elem in elem:
                 cmp_text = None
                 cmp_text = None
                 if cmp_type == "attribute":
                 if cmp_type == "attribute":
                     if add_arg in elem.attrib:
                     if add_arg in elem.attrib:
                         cmp_text = elem.attrib[add_arg]
                         cmp_text = elem.attrib[add_arg]
-                
+
                 elif cmp_type == "element_content":
                 elif cmp_type == "element_content":
                     cmp_text = elem.text
                     cmp_text = elem.text
-                
+
                 elif cmp_type == "child_element_content":
                 elif cmp_type == "child_element_content":
                     cmp = elem.find(self.xml_ns.Ns(add_arg))
                     cmp = elem.find(self.xml_ns.Ns(add_arg))
                     if cmp is not None:
                     if cmp is not None:
                         cmp_text = cmp.text
                         cmp_text = cmp.text
-                
+
                 if cmp_text is None or \
                 if cmp_text is None or \
                    cmp_text.lower() == parent_cmp_text.lower():
                    cmp_text.lower() == parent_cmp_text.lower():
                     is_there = True
                     is_there = True
                     break
                     break
-            
+
             if not is_there:
             if not is_there:
                 layer.append(par_elem)
                 layer.append(par_elem)
 
 
     def _find(self, etreeElement, tag):
     def _find(self, etreeElement, tag):
         """!Find child element.
         """!Find child element.
-            If the element is not found it raises xml.etree.ElementTree.ParseError.  
+            If the element is not found it raises xml.etree.ElementTree.ParseError.
         """
         """
         res = etreeElement.find(self.xml_ns.Ns(tag))
         res = etreeElement.find(self.xml_ns.Ns(tag))
 
 
@@ -231,7 +237,7 @@ class WMSCapabilitiesTree(BaseCapabilitiesTree):
 
 
     def _findall(self, etreeElement, tag):
     def _findall(self, etreeElement, tag):
         """!Find all children element.
         """!Find all children element.
-            If no element is found it raises xml.etree.ElementTree.ParseError.  
+            If no element is found it raises xml.etree.ElementTree.ParseError.
         """
         """
         res = etreeElement.findall(self.xml_ns.Ns(tag))
         res = etreeElement.findall(self.xml_ns.Ns(tag))
 
 
@@ -251,9 +257,11 @@ class WMSCapabilitiesTree(BaseCapabilitiesTree):
         """
         """
         return self.xml_ns
         return self.xml_ns
 
 
+
 class WMTSXMLNsHandler:
 class WMTSXMLNsHandler:
     """!Handle XML namespaces which are used in WMTS capabilities file.
     """!Handle XML namespaces which are used in WMTS capabilities file.
     """
     """
+
     def NsWmts(self, tag):
     def NsWmts(self, tag):
         """!Add namespace.
         """!Add namespace.
         """
         """
@@ -264,19 +272,21 @@ class WMTSXMLNsHandler:
         """
         """
         return "{http://www.opengis.net/ows/1.1}" + tag
         return "{http://www.opengis.net/ows/1.1}" + tag
 
 
+
 class WMTSCapabilitiesTree(BaseCapabilitiesTree):
 class WMTSCapabilitiesTree(BaseCapabilitiesTree):
+
     def __init__(self, cap_file):
     def __init__(self, cap_file):
         """!Parses WMTS capabilities file.
         """!Parses WMTS capabilities file.
             If the capabilities file cannot be parsed it raises xml.etree.ElementTree.ParseError.
             If the capabilities file cannot be parsed it raises xml.etree.ElementTree.ParseError.
 
 
-        The class also removes elements which are in invalid form and are needed 
+        The class also removes elements which are in invalid form and are needed
         by wxGUI capabilities dialog or for creation of GetTile request by GRASS WMS library.
         by wxGUI capabilities dialog or for creation of GetTile request by GRASS WMS library.
 
 
-        @param cap_file - capabilities file        
+        @param cap_file - capabilities file
         """
         """
         BaseCapabilitiesTree.__init__(self, cap_file)
         BaseCapabilitiesTree.__init__(self, cap_file)
         self.xml_ns = WMTSXMLNsHandler()
         self.xml_ns = WMTSXMLNsHandler()
-        
+
         grass.debug('Checking WMTS capabilities tree.', 4)
         grass.debug('Checking WMTS capabilities tree.', 4)
 
 
         contents = self._find(self.getroot(), 'Contents', self.xml_ns.NsWmts)
         contents = self._find(self.getroot(), 'Contents', self.xml_ns.NsWmts)
@@ -320,8 +330,8 @@ class WMTSCapabilitiesTree(BaseCapabilitiesTree):
 
 
         for t_mat in tile_mats:
         for t_mat in tile_mats:
             if not self._checkMat(t_mat):
             if not self._checkMat(t_mat):
-               grass.debug('Removed invalid <TileMatrix> element.', 4)
-               mat_set.remove(t_mat)
+                grass.debug('Removed invalid <TileMatrix> element.', 4)
+                mat_set.remove(t_mat)
 
 
         tile_mats = mat_set.findall(self.xml_ns.NsWmts('TileMatrix'))
         tile_mats = mat_set.findall(self.xml_ns.NsWmts('TileMatrix'))
         if not tile_mats:
         if not tile_mats:
@@ -329,12 +339,12 @@ class WMTSCapabilitiesTree(BaseCapabilitiesTree):
 
 
         return True
         return True
 
 
-    def _checkMat(self, t_mat):        
+    def _checkMat(self, t_mat):
         """!Check <TileMatrix>.
         """!Check <TileMatrix>.
         """
         """
         def _checkElement(t_mat, e, func):
         def _checkElement(t_mat, e, func):
             element = t_mat.find(self.xml_ns.NsWmts(e))
             element = t_mat.find(self.xml_ns.NsWmts(e))
-            if element is None or not element.text: 
+            if element is None or not element.text:
                 return False
                 return False
 
 
             try:
             try:
@@ -346,12 +356,12 @@ class WMTSCapabilitiesTree(BaseCapabilitiesTree):
                 return False
                 return False
             return True
             return True
 
 
-        for e, func in [['ScaleDenominator', float], 
-                        ['TileWidth', int], 
+        for e, func in [['ScaleDenominator', float],
+                        ['TileWidth', int],
                         ['TileHeight', int]]:
                         ['TileHeight', int]]:
             if not _checkElement(t_mat, e, func):
             if not _checkElement(t_mat, e, func):
                 return False
                 return False
-                        
+
         tile_mat_id = t_mat.find(self.xml_ns.NsOws('Identifier'))
         tile_mat_id = t_mat.find(self.xml_ns.NsOws('Identifier'))
         if tile_mat_id is None or not tile_mat_id.text:
         if tile_mat_id is None or not tile_mat_id.text:
             return False
             return False
@@ -364,13 +374,13 @@ class WMTSCapabilitiesTree(BaseCapabilitiesTree):
         if len(tl) < 2:
         if len(tl) < 2:
             return False
             return False
 
 
-        for t in tl:              
+        for t in tl:
             try:
             try:
                 t = float(t)
                 t = float(t)
             except ValueError:
             except ValueError:
                 return False
                 return False
         return True
         return True
-    
+
     def _checkLayer(self, layer):
     def _checkLayer(self, layer):
         """!Check <Layer> element.
         """!Check <Layer> element.
         """
         """
@@ -395,7 +405,7 @@ class WMTSCapabilitiesTree(BaseCapabilitiesTree):
         contents = self.getroot().find(self.xml_ns.NsWmts('Contents'))
         contents = self.getroot().find(self.xml_ns.NsWmts('Contents'))
         mat_sets = contents.findall(self.xml_ns.NsWmts('TileMatrixSet'))
         mat_sets = contents.findall(self.xml_ns.NsWmts('TileMatrixSet'))
 
 
-        for link in  mat_set_links:
+        for link in mat_set_links:
             # <TileMatrixSetLink> does not point to existing  <TileMatrixSet>
             # <TileMatrixSetLink> does not point to existing  <TileMatrixSet>
             if not self._checkMatSetLink(link, mat_sets):
             if not self._checkMatSetLink(link, mat_sets):
                 grass.debug('Removed invalid <TileMatrixSetLink> element.', 4)
                 grass.debug('Removed invalid <TileMatrixSetLink> element.', 4)
@@ -433,7 +443,7 @@ class WMTSCapabilitiesTree(BaseCapabilitiesTree):
             if not tile_mat_limits:
             if not tile_mat_limits:
                 grass.debug('Removed invalid <TileMatrixSetLimits> element.', 4)
                 grass.debug('Removed invalid <TileMatrixSetLimits> element.', 4)
                 link.remove(tile_mat_set_limits)
                 link.remove(tile_mat_set_limits)
-          
+
         if not found:
         if not found:
             return False
             return False
 
 
@@ -456,9 +466,9 @@ class WMTSCapabilitiesTree(BaseCapabilitiesTree):
                 return False
                 return False
         return True
         return True
 
 
-    def _find(self, etreeElement, tag, ns = None):
+    def _find(self, etreeElement, tag, ns=None):
         """!Find child element.
         """!Find child element.
-            If the element is not found it raises xml.etree.ElementTree.ParseError.  
+            If the element is not found it raises xml.etree.ElementTree.ParseError.
         """
         """
         if not ns:
         if not ns:
             res = etreeElement.find(tag)
             res = etreeElement.find(tag)
@@ -471,9 +481,9 @@ class WMTSCapabilitiesTree(BaseCapabilitiesTree):
 
 
         return res
         return res
 
 
-    def _findall(self, etreeElement, tag, ns = None):
+    def _findall(self, etreeElement, tag, ns=None):
         """!Find all children element.
         """!Find all children element.
-            If no element is found it raises xml.etree.ElementTree.ParseError.  
+            If no element is found it raises xml.etree.ElementTree.ParseError.
         """
         """
         if not ns:
         if not ns:
             res = etreeElement.findall(tag)
             res = etreeElement.findall(tag)
@@ -491,15 +501,17 @@ class WMTSCapabilitiesTree(BaseCapabilitiesTree):
         """
         """
         return self.xml_ns
         return self.xml_ns
 
 
+
 class OnEarthCapabilitiesTree(BaseCapabilitiesTree):
 class OnEarthCapabilitiesTree(BaseCapabilitiesTree):
+
     def __init__(self, cap_file):
     def __init__(self, cap_file):
         """!Parse NASA OnEarth tile service file.
         """!Parse NASA OnEarth tile service file.
             If the file cannot be parsed it raises xml.etree.ElementTree.ParseError.
             If the file cannot be parsed it raises xml.etree.ElementTree.ParseError.
 
 
-        The class also removes elements which are in invalid form and are needed 
+        The class also removes elements which are in invalid form and are needed
         by wxGUI capabilities dialog or for creation of GetMap request by GRASS WMS library.
         by wxGUI capabilities dialog or for creation of GetMap request by GRASS WMS library.
 
 
-        @param cap_file - capabilities file        
+        @param cap_file - capabilities file
         """
         """
         BaseCapabilitiesTree.__init__(self, cap_file)
         BaseCapabilitiesTree.__init__(self, cap_file)
 
 
@@ -509,7 +521,7 @@ class OnEarthCapabilitiesTree(BaseCapabilitiesTree):
 
 
         grass.debug('Check if OnEarth capabilities tree was finished.', 4)
         grass.debug('Check if OnEarth capabilities tree was finished.', 4)
 
 
-    def _checkLayerTree(self, parent_layer, first = True):
+    def _checkLayerTree(self, parent_layer, first=True):
         """!Recursively check layer tree.
         """!Recursively check layer tree.
         """
         """
         if first:
         if first:
@@ -526,11 +538,11 @@ class OnEarthCapabilitiesTree(BaseCapabilitiesTree):
                 grass.debug(('Removed invalid <%s> element.' % l.tag), 4)
                 grass.debug(('Removed invalid <%s> element.' % l.tag), 4)
                 parent_layer.remove(l)
                 parent_layer.remove(l)
             if l.tag == 'TiledGroups':
             if l.tag == 'TiledGroups':
-               self._checkLayerTree(l, False)
+                self._checkLayerTree(l, False)
 
 
     def _find(self, etreeElement, tag):
     def _find(self, etreeElement, tag):
         """!Find child element.
         """!Find child element.
-            If the element is not found it raises xml.etree.ElementTree.ParseError.  
+            If the element is not found it raises xml.etree.ElementTree.ParseError.
         """
         """
         res = etreeElement.find(tag)
         res = etreeElement.find(tag)
 
 
@@ -545,7 +557,7 @@ class OnEarthCapabilitiesTree(BaseCapabilitiesTree):
         """
         """
         if layer.tag == 'TiledGroups':
         if layer.tag == 'TiledGroups':
             return True
             return True
-            
+
         name = layer.find('Name')
         name = layer.find('Name')
         if name is None or not name.text:
         if name is None or not name.text:
             return False
             return False
@@ -574,7 +586,7 @@ class OnEarthCapabilitiesTree(BaseCapabilitiesTree):
         """!Get all urls from tile pattern.
         """!Get all urls from tile pattern.
         """
         """
         urls = []
         urls = []
-        if  tile_pattern.text is not None:
+        if tile_pattern.text is not None:
             tile_patt_lines = tile_pattern.text.split('\n')
             tile_patt_lines = tile_pattern.text.split('\n')
 
 
             for line in tile_patt_lines:
             for line in tile_patt_lines:
@@ -585,7 +597,7 @@ class OnEarthCapabilitiesTree(BaseCapabilitiesTree):
     def gettilepatternurldata(self, url):
     def gettilepatternurldata(self, url):
         """!Parse url string in Tile Pattern.
         """!Parse url string in Tile Pattern.
         """
         """
-        par_url = bbox = width = height = None 
+        par_url = bbox = width = height = None
 
 
         bbox_idxs = self.geturlparamidxs(url, "bbox=")
         bbox_idxs = self.geturlparamidxs(url, "bbox=")
         if bbox_idxs is None:
         if bbox_idxs is None:
@@ -593,7 +605,7 @@ class OnEarthCapabilitiesTree(BaseCapabilitiesTree):
 
 
         par_url = [url[:bbox_idxs[0] - 1], url[bbox_idxs[1]:]]
         par_url = [url[:bbox_idxs[0] - 1], url[bbox_idxs[1]:]]
 
 
-        bbox = url[bbox_idxs[0] + len('bbox=') : bbox_idxs[1]]
+        bbox = url[bbox_idxs[0] + len('bbox='): bbox_idxs[1]]
         bbox_list = bbox.split(',')
         bbox_list = bbox.split(',')
         if len(bbox_list) < 4:
         if len(bbox_list) < 4:
             return None
             return None
@@ -608,8 +620,8 @@ class OnEarthCapabilitiesTree(BaseCapabilitiesTree):
             return None
             return None
 
 
         try:
         try:
-            width = int(url[width_idxs[0] + len('width=') : width_idxs[1]])
-        except  ValueError:
+            width = int(url[width_idxs[0] + len('width='): width_idxs[1]])
+        except ValueError:
             return None
             return None
 
 
         height_idxs = self.geturlparamidxs(url, "height=")
         height_idxs = self.geturlparamidxs(url, "height=")
@@ -617,8 +629,8 @@ class OnEarthCapabilitiesTree(BaseCapabilitiesTree):
             return None
             return None
 
 
         try:
         try:
-            height = int(url[height_idxs[0] + len('height=') : height_idxs[1]])
-        except  ValueError:
+            height = int(url[height_idxs[0] + len('height='): height_idxs[1]])
+        except ValueError:
             return None
             return None
 
 
         if height < 0 or width < 0:
         if height < 0 or width < 0:
@@ -630,7 +642,7 @@ class OnEarthCapabilitiesTree(BaseCapabilitiesTree):
         """!Find start and end index of parameter and it's value in url string
         """!Find start and end index of parameter and it's value in url string
         """
         """
         start_i = params_str.lower().find(param_key)
         start_i = params_str.lower().find(param_key)
-        if start_i < 0: 
+        if start_i < 0:
             return None
             return None
         end_i = params_str.find("&", start_i)
         end_i = params_str.find("&", start_i)
         if end_i < 0:
         if end_i < 0:

파일 크기가 너무 크기때문에 변경 상태를 표시하지 않습니다.
+ 305 - 217
scripts/r.in.wms/wms_drv.py


+ 57 - 53
scripts/r.in.wms/wms_gdal_drv.py

@@ -1,5 +1,5 @@
 """!
 """!
-@brief GDAL WMS driver. 
+@brief GDAL WMS driver.
 
 
 List of classes:
 List of classes:
  - wms_drv::NullDevice
  - wms_drv::NullDevice
@@ -14,7 +14,7 @@ This program is free software under the GNU General Public License
 """
 """
 
 
 import os
 import os
-import grass.script as grass 
+import grass.script as grass
 
 
 try:
 try:
     from osgeo import gdal
     from osgeo import gdal
@@ -26,129 +26,133 @@ import xml.etree.ElementTree as etree
 
 
 from wms_base import WMSBase, GetSRSParamVal
 from wms_base import WMSBase, GetSRSParamVal
 
 
+
 class NullDevice():
 class NullDevice():
+
     def write(self, s):
     def write(self, s):
         pass
         pass
 
 
+
 class WMSGdalDrv(WMSBase):
 class WMSGdalDrv(WMSBase):
+
     def _createXML(self):
     def _createXML(self):
         """!Create XML for GDAL WMS driver
         """!Create XML for GDAL WMS driver
-        
+
         @return path to XML file
         @return path to XML file
         """
         """
         self._debug("_createXML", "started")
         self._debug("_createXML", "started")
-        
+
         gdal_wms = etree.Element("GDAL_WMS")
         gdal_wms = etree.Element("GDAL_WMS")
         service = etree.SubElement(gdal_wms, "Service")
         service = etree.SubElement(gdal_wms, "Service")
         name = etree.Element("name")
         name = etree.Element("name")
-        service.set("name","WMS")
-        
+        service.set("name", "WMS")
+
         version = etree.SubElement(service, "Version")
         version = etree.SubElement(service, "Version")
-        version.text =self.params['wms_version']
-        
+        version.text = self.params['wms_version']
+
         server_url = etree.SubElement(service, "ServerUrl")
         server_url = etree.SubElement(service, "ServerUrl")
-        server_url.text =self.params['url']
-        
-        srs = etree.SubElement(service, self.params['proj_name'])   
+        server_url.text = self.params['url']
+
+        srs = etree.SubElement(service, self.params['proj_name'])
         srs.text = GetSRSParamVal(self.params['srs'])
         srs.text = GetSRSParamVal(self.params['srs'])
-        
+
         image_format = etree.SubElement(service, "ImageFormat")
         image_format = etree.SubElement(service, "ImageFormat")
         image_format.text = self.params['format']
         image_format.text = self.params['format']
-        
+
         image_format = etree.SubElement(service, "Transparent")
         image_format = etree.SubElement(service, "Transparent")
         image_format.text = self.params['transparent']
         image_format.text = self.params['transparent']
-        
+
         layers = etree.SubElement(service, "Layers")
         layers = etree.SubElement(service, "Layers")
         layers.text = self.params['layers']
         layers.text = self.params['layers']
-        
+
         styles = etree.SubElement(service, "Styles")
         styles = etree.SubElement(service, "Styles")
         styles.text = self.params['styles']
         styles.text = self.params['styles']
-        
+
         data_window = etree.SubElement(gdal_wms, "DataWindow")
         data_window = etree.SubElement(gdal_wms, "DataWindow")
 
 
         upper_left_x = etree.SubElement(data_window, "UpperLeftX")
         upper_left_x = etree.SubElement(data_window, "UpperLeftX")
-        upper_left_x.text = str(self.bbox['minx']) 
-        
+        upper_left_x.text = str(self.bbox['minx'])
+
         upper_left_y = etree.SubElement(data_window, "UpperLeftY")
         upper_left_y = etree.SubElement(data_window, "UpperLeftY")
-        upper_left_y.text = str(self.bbox['maxy']) 
-        
+        upper_left_y.text = str(self.bbox['maxy'])
+
         lower_right_x = etree.SubElement(data_window, "LowerRightX")
         lower_right_x = etree.SubElement(data_window, "LowerRightX")
-        lower_right_x.text = str(self.bbox['maxx']) 
-        
+        lower_right_x.text = str(self.bbox['maxx'])
+
         lower_right_y = etree.SubElement(data_window, "LowerRightY")
         lower_right_y = etree.SubElement(data_window, "LowerRightY")
         lower_right_y.text = str(self.bbox['miny'])
         lower_right_y.text = str(self.bbox['miny'])
-        
+
         size_x = etree.SubElement(data_window, "SizeX")
         size_x = etree.SubElement(data_window, "SizeX")
-        size_x.text = str(self.region['cols']) 
-        
+        size_x.text = str(self.region['cols'])
+
         size_y = etree.SubElement(data_window, "SizeY")
         size_y = etree.SubElement(data_window, "SizeY")
-        size_y.text = str(self.region['rows']) 
-        
+        size_y.text = str(self.region['rows'])
+
         # RGB + alpha
         # RGB + alpha
         self.temp_map_bands_num = 4
         self.temp_map_bands_num = 4
         block_size_x = etree.SubElement(gdal_wms, "BandsCount")
         block_size_x = etree.SubElement(gdal_wms, "BandsCount")
         block_size_x.text = str(self.temp_map_bands_num)
         block_size_x.text = str(self.temp_map_bands_num)
-        
+
         block_size_x = etree.SubElement(gdal_wms, "BlockSizeX")
         block_size_x = etree.SubElement(gdal_wms, "BlockSizeX")
-        block_size_x.text = str(self.tile_size['cols']) 
-        
+        block_size_x.text = str(self.tile_size['cols'])
+
         block_size_y = etree.SubElement(gdal_wms, "BlockSizeY")
         block_size_y = etree.SubElement(gdal_wms, "BlockSizeY")
         block_size_y.text = str(self.tile_size['rows'])
         block_size_y.text = str(self.tile_size['rows'])
-        
+
         xml_file = self._tempfile()
         xml_file = self._tempfile()
-        
+
         etree.ElementTree(gdal_wms).write(xml_file)
         etree.ElementTree(gdal_wms).write(xml_file)
-        
+
         self._debug("_createXML", "finished -> %s" % xml_file)
         self._debug("_createXML", "finished -> %s" % xml_file)
-        
+
         return xml_file
         return xml_file
-    
+
     def _download(self):
     def _download(self):
         """!Downloads data from WMS server using GDAL WMS driver
         """!Downloads data from WMS server using GDAL WMS driver
-        
+
         @return temp_map with stored downloaded data
         @return temp_map with stored downloaded data
         """
         """
         grass.message("Downloading data from WMS server...")
         grass.message("Downloading data from WMS server...")
 
 
-        # GDAL WMS driver does not flip geographic coordinates 
+        # GDAL WMS driver does not flip geographic coordinates
         # according to WMS standard 1.3.0.
         # according to WMS standard 1.3.0.
-        if ("+proj=latlong" in self.proj_srs or \
-            "+proj=longlat" in self.proj_srs) and \
-            self.params['wms_version'] == "1.3.0":
+        if ("+proj=latlong" in self.proj_srs or
+                "+proj=longlat" in self.proj_srs) and \
+                self.params['wms_version'] == "1.3.0":
             grass.warning(_("If module will not be able to fetch the data in this " +
             grass.warning(_("If module will not be able to fetch the data in this " +
                             "geographic projection, \n try 'WMS_GRASS' driver or use WMS version 1.1.1."))
                             "geographic projection, \n try 'WMS_GRASS' driver or use WMS version 1.1.1."))
 
 
         self._debug("_download", "started")
         self._debug("_download", "started")
-        
-        temp_map = self._tempfile()        
+
+        temp_map = self._tempfile()
 
 
         xml_file = self._createXML()
         xml_file = self._createXML()
         wms_dataset = gdal.Open(xml_file, gdal.GA_ReadOnly)
         wms_dataset = gdal.Open(xml_file, gdal.GA_ReadOnly)
         grass.try_remove(xml_file)
         grass.try_remove(xml_file)
         if wms_dataset is None:
         if wms_dataset is None:
             grass.fatal(_("Unable to open GDAL WMS driver"))
             grass.fatal(_("Unable to open GDAL WMS driver"))
-        
+
         self._debug("_download", "GDAL dataset created")
         self._debug("_download", "GDAL dataset created")
-        
+
         driver = gdal.GetDriverByName(self.gdal_drv_format)
         driver = gdal.GetDriverByName(self.gdal_drv_format)
         if driver is None:
         if driver is None:
             grass.fatal(_("Unable to find %s driver" % format))
             grass.fatal(_("Unable to find %s driver" % format))
-        
+
         metadata = driver.GetMetadata()
         metadata = driver.GetMetadata()
-        if not metadata.has_key(gdal.DCAP_CREATECOPY) or \
+        if gdal.DCAP_CREATECOPY not in metadata or \
            metadata[gdal.DCAP_CREATECOPY] == 'NO':
            metadata[gdal.DCAP_CREATECOPY] == 'NO':
             grass.fatal(_('Driver %s supports CreateCopy() method.') % self.gdal_drv_name)
             grass.fatal(_('Driver %s supports CreateCopy() method.') % self.gdal_drv_name)
-        
+
         self._debug("_download", "calling GDAL CreateCopy...")
         self._debug("_download", "calling GDAL CreateCopy...")
-        
+
         temp_map_dataset = driver.CreateCopy(temp_map, wms_dataset, 0)
         temp_map_dataset = driver.CreateCopy(temp_map, wms_dataset, 0)
-        
+
         if temp_map_dataset is None:
         if temp_map_dataset is None:
             grass.fatal(_("Incorrect WMS query"))
             grass.fatal(_("Incorrect WMS query"))
-        
-        temp_map_dataset  = None
+
+        temp_map_dataset = None
         wms_dataset = None
         wms_dataset = None
-        
+
         self._debug("_download", "finished")
         self._debug("_download", "finished")
-        
+
         return temp_map
         return temp_map

+ 29 - 21
scripts/r.mask/r.mask.py

@@ -75,11 +75,12 @@ from grass.exceptions import CalledModuleError
 
 
 def cleanup():
 def cleanup():
     if tmp:
     if tmp:
-        grass.run_command('g.remove', flags = 'f', type = 'raster',
-                          name = tmp, quiet = True)
+        grass.run_command('g.remove', flags='f', type='raster',
+                          name=tmp, quiet=True)
     if tmp_hull:
     if tmp_hull:
-        grass.run_command('g.remove', flags = 'f', type = 'vector',
-                          name = tmp_hull, quiet = True)
+        grass.run_command('g.remove', flags='f', type='vector',
+                          name=tmp_hull, quiet=True)
+
 
 
 def main():
 def main():
     raster = options['raster']
     raster = options['raster']
@@ -95,13 +96,13 @@ def main():
         grass.fatal(_("Either parameter <raster> ot parameter <vector> is required"))
         grass.fatal(_("Either parameter <raster> ot parameter <vector> is required"))
 
 
     mapset = grass.gisenv()['MAPSET']
     mapset = grass.gisenv()['MAPSET']
-    exists = bool(grass.find_file('MASK', element = 'cell', mapset = mapset)['file'])
+    exists = bool(grass.find_file('MASK', element='cell', mapset=mapset)['file'])
 
 
     if remove:
     if remove:
         # -> remove
         # -> remove
         if exists:
         if exists:
-            grass.run_command('g.remove', flags = 'f', quiet = True,
-                              type = 'raster', name = 'MASK')
+            grass.run_command('g.remove', flags='f', quiet=True,
+                              type='raster', name='MASK')
             grass.message(_("Raster MASK removed"))
             grass.message(_("Raster MASK removed"))
         else:
         else:
             grass.fatal(_("No existing MASK to remove"))
             grass.fatal(_("No existing MASK to remove"))
@@ -112,9 +113,9 @@ def main():
                 grass.fatal(_("MASK already found in current mapset. Delete first or overwrite."))
                 grass.fatal(_("MASK already found in current mapset. Delete first or overwrite."))
             else:
             else:
                 grass.warning(_("MASK already exists and will be overwritten"))
                 grass.warning(_("MASK already exists and will be overwritten"))
-                grass.run_command('g.remove', flags = 'f', quiet = True,
-                                  type = 'raster', name = 'MASK')
-        
+                grass.run_command('g.remove', flags='f', quiet=True,
+                                  type='raster', name='MASK')
+
         if raster:
         if raster:
             # check if input raster exists
             # check if input raster exists
             if not grass.find_file(raster)['file']:
             if not grass.find_file(raster)['file']:
@@ -125,7 +126,12 @@ def main():
                     grass.fatal(_("The raster map <%s> must be integer (CELL type) "
                     grass.fatal(_("The raster map <%s> must be integer (CELL type) "
                                   " in order to use the 'maskcats' parameter") % raster)
                                   " in order to use the 'maskcats' parameter") % raster)
 
 
-            p = grass.feed_command('r.reclass', input = raster, output = 'MASK', overwrite = True, rules = '-')
+            p = grass.feed_command(
+                'r.reclass',
+                input=raster,
+                output='MASK',
+                overwrite=True,
+                rules='-')
             p.stdin.write("%s = 1" % maskcats)
             p.stdin.write("%s = 1" % maskcats)
             p.stdin.close()
             p.stdin.close()
             p.wait()
             p.wait()
@@ -133,13 +139,13 @@ def main():
             vector_name = grass.find_file(vector, 'vector')['fullname']
             vector_name = grass.find_file(vector, 'vector')['fullname']
             if not vector_name:
             if not vector_name:
                 grass.fatal(_("Vector map <%s> not found") % vector)
                 grass.fatal(_("Vector map <%s> not found") % vector)
-            
+
             # parser bug?
             # parser bug?
             if len(cats) == 0:
             if len(cats) == 0:
                 cats = None
                 cats = None
             if len(where) == 0:
             if len(where) == 0:
                 where = None
                 where = None
-            
+
             if grass.vector_info_topo(vector_name)['areas'] < 1:
             if grass.vector_info_topo(vector_name)['areas'] < 1:
                 grass.warning(_("No area found in vector map <%s>. "
                 grass.warning(_("No area found in vector map <%s>. "
                                 "Creating a convex hull for MASK.") % vector_name)
                                 "Creating a convex hull for MASK.") % vector_name)
@@ -152,23 +158,25 @@ def main():
                                       input=vector_name, output=tmp_hull,
                                       input=vector_name, output=tmp_hull,
                                       layer=layer, cats=cats, where=where)
                                       layer=layer, cats=cats, where=where)
                 except CalledModuleError:
                 except CalledModuleError:
-                    grass.fatal(_("Unable to create a convex hull for vector map <%s>") % vector_name)
+                    grass.fatal(
+                        _("Unable to create a convex hull for vector map <%s>") %
+                        vector_name)
             else:
             else:
                 to_rast_input = vector_name
                 to_rast_input = vector_name
-            
+
             env = os.environ.copy()
             env = os.environ.copy()
             if grass.verbosity() > 1:
             if grass.verbosity() > 1:
                 env['GRASS_VERBOSE'] = '1'
                 env['GRASS_VERBOSE'] = '1'
-            grass.run_command('v.to.rast', input = to_rast_input, layer = layer,
-                              output = 'MASK', use = 'val', val = '1',
-                              type = 'area', cats = cats, where = where, env = env)
-        
+            grass.run_command('v.to.rast', input=to_rast_input, layer=layer,
+                              output='MASK', use='val', val='1',
+                              type='area', cats=cats, where=where, env=env)
+
         if invert:
         if invert:
             global tmp
             global tmp
             tmp = "r_mask_%d" % os.getpid()
             tmp = "r_mask_%d" % os.getpid()
-            grass.run_command('g.rename', raster = ('MASK', tmp), quiet = True)
+            grass.run_command('g.rename', raster=('MASK', tmp), quiet=True)
             grass.message(_("Creating inverted raster MASK..."))
             grass.message(_("Creating inverted raster MASK..."))
-            grass.mapcalc("MASK = if(isnull($tmp), 1, null())", tmp = tmp)
+            grass.mapcalc("MASK = if(isnull($tmp), 1, null())", tmp=tmp)
             grass.verbose(_("Inverted raster MASK created"))
             grass.verbose(_("Inverted raster MASK created"))
         else:
         else:
             grass.verbose(_("Raster MASK created"))
             grass.verbose(_("Raster MASK created"))

+ 1 - 0
scripts/r.out.xyz/r.out.xyz.py

@@ -37,6 +37,7 @@ import sys
 from grass.script import core as grass
 from grass.script import core as grass
 from grass.exceptions import CalledModuleError
 from grass.exceptions import CalledModuleError
 
 
+
 def main():
 def main():
     # if no output filename, output to stdout
     # if no output filename, output to stdout
     output = options['output']
     output = options['output']

+ 19 - 17
scripts/r.pack/r.pack.py

@@ -40,9 +40,11 @@ import tarfile
 from grass.script.utils import try_rmdir, try_remove
 from grass.script.utils import try_rmdir, try_remove
 from grass.script import core as grass
 from grass.script import core as grass
 
 
+
 def cleanup():
 def cleanup():
     try_rmdir(tmp)
     try_rmdir(tmp)
 
 
+
 def main():
 def main():
     infile = options['input']
     infile = options['input']
     compression_off = flags['c']
     compression_off = flags['c']
@@ -54,30 +56,30 @@ def main():
         outfile_path, outfile_base = os.path.split(os.path.abspath(options['output']))
         outfile_path, outfile_base = os.path.split(os.path.abspath(options['output']))
     else:
     else:
         outfile_path, outfile_base = os.path.split(os.path.abspath(infile + ".pack"))
         outfile_path, outfile_base = os.path.split(os.path.abspath(infile + ".pack"))
-    
+
     outfile = os.path.join(outfile_path, outfile_base)
     outfile = os.path.join(outfile_path, outfile_base)
-    
+
     global tmp
     global tmp
     tmp = grass.tempdir()
     tmp = grass.tempdir()
     tmp_dir = os.path.join(tmp, infile)
     tmp_dir = os.path.join(tmp, infile)
     os.mkdir(tmp_dir)
     os.mkdir(tmp_dir)
     grass.debug('tmp_dir = %s' % tmp_dir)
     grass.debug('tmp_dir = %s' % tmp_dir)
-    
-    gfile = grass.find_file(name = infile, element = 'cell', mapset = mapset)
+
+    gfile = grass.find_file(name=infile, element='cell', mapset=mapset)
     if not gfile['name']:
     if not gfile['name']:
         grass.fatal(_("Raster map <%s> not found") % infile)
         grass.fatal(_("Raster map <%s> not found") % infile)
-    
+
     if os.path.exists(outfile):
     if os.path.exists(outfile):
         if os.getenv('GRASS_OVERWRITE'):
         if os.getenv('GRASS_OVERWRITE'):
             grass.warning(_("Pack file <%s> already exists and will be overwritten") % outfile)
             grass.warning(_("Pack file <%s> already exists and will be overwritten") % outfile)
             try_remove(outfile)
             try_remove(outfile)
         else:
         else:
             grass.fatal(_("option <output>: <%s> exists.") % outfile)
             grass.fatal(_("option <output>: <%s> exists.") % outfile)
-    
+
     grass.message(_("Packing <%s> to <%s>...") % (gfile['fullname'], outfile))
     grass.message(_("Packing <%s> to <%s>...") % (gfile['fullname'], outfile))
     basedir = os.path.sep.join(os.path.normpath(gfile['file']).split(os.path.sep)[:-2])
     basedir = os.path.sep.join(os.path.normpath(gfile['file']).split(os.path.sep)[:-2])
-    olddir  = os.getcwd()
-    
+    olddir = os.getcwd()
+
     # copy elements
     # copy elements
     for element in ['cats', 'cell', 'cellhd', 'colr', 'fcell', 'hist']:
     for element in ['cats', 'cell', 'cellhd', 'colr', 'fcell', 'hist']:
         path = os.path.join(basedir, element, infile)
         path = os.path.join(basedir, element, infile)
@@ -85,14 +87,14 @@ def main():
             grass.debug('copying %s' % path)
             grass.debug('copying %s' % path)
             shutil.copyfile(path,
             shutil.copyfile(path,
                             os.path.join(tmp_dir, element))
                             os.path.join(tmp_dir, element))
-            
+
     if os.path.exists(os.path.join(basedir, 'cell_misc', infile)):
     if os.path.exists(os.path.join(basedir, 'cell_misc', infile)):
         shutil.copytree(os.path.join(basedir, 'cell_misc', infile),
         shutil.copytree(os.path.join(basedir, 'cell_misc', infile),
                         os.path.join(tmp_dir, 'cell_misc'))
                         os.path.join(tmp_dir, 'cell_misc'))
-        
+
     if not os.listdir(tmp_dir):
     if not os.listdir(tmp_dir):
         grass.fatal(_("No raster map components found"))
         grass.fatal(_("No raster map components found"))
-                    
+
     # copy projection info
     # copy projection info
     # (would prefer to use g.proj*, but this way is 5.3 and 5.7 compat)
     # (would prefer to use g.proj*, but this way is 5.3 and 5.7 compat)
     gisenv = grass.gisenv()
     gisenv = grass.gisenv()
@@ -101,22 +103,22 @@ def main():
                             'PERMANENT', 'PROJ_' + support)
                             'PERMANENT', 'PROJ_' + support)
         if os.path.exists(path):
         if os.path.exists(path):
             shutil.copyfile(path, os.path.join(tmp_dir, 'PROJ_' + support))
             shutil.copyfile(path, os.path.join(tmp_dir, 'PROJ_' + support))
-    
+
     # pack it all up
     # pack it all up
     os.chdir(tmp)
     os.chdir(tmp)
     if compression_off:
     if compression_off:
-        tar = tarfile.TarFile.open(name = outfile_base, mode = 'w:')
+        tar = tarfile.TarFile.open(name=outfile_base, mode='w:')
     else:
     else:
-        tar = tarfile.TarFile.open(name = outfile_base, mode = 'w:gz')
-    tar.add(infile, recursive = True)
+        tar = tarfile.TarFile.open(name=outfile_base, mode='w:gz')
+    tar.add(infile, recursive=True)
     tar.close()
     tar.close()
     try:
     try:
         shutil.move(outfile_base, outfile)
         shutil.move(outfile_base, outfile)
     except shutil.Error as e:
     except shutil.Error as e:
         grass.fatal(e)
         grass.fatal(e)
-        
+
     os.chdir(olddir)
     os.chdir(olddir)
-    
+
     grass.verbose(_("Raster map saved to '%s'" % outfile))
     grass.verbose(_("Raster map saved to '%s'" % outfile))
 
 
 
 

+ 29 - 29
scripts/r.plane/r.plane.py

@@ -59,38 +59,37 @@
 #%end
 #%end
 #%option
 #%option
 #% key: type
 #% key: type
-#% type: string 
+#% type: string
 #% options: CELL,FCELL,DCELL
 #% options: CELL,FCELL,DCELL
 #% description: Type of raster map to be created
 #% description: Type of raster map to be created
 #% answer: FCELL
 #% answer: FCELL
 #%end
 #%end
 
 
-import sys
-import os
 import math
 import math
 import string
 import string
-import grass.script as grass
+import grass.script as gscript
+
 
 
 def main():
 def main():
     name = options['output']
     name = options['output']
     type = options['type']
     type = options['type']
     dip = float(options['dip'])
     dip = float(options['dip'])
-    az  = float(options['azimuth'])
-    ea  = float(options['easting'])
-    no  = float(options['northing'])
-    el  = float(options['elevation'])
+    az = float(options['azimuth'])
+    ea = float(options['easting'])
+    no = float(options['northing'])
+    el = float(options['elevation'])
 
 
-    reg = grass.region()
+    # reg = gscript.region()
 
 
     ### test input values ###
     ### test input values ###
     if abs(dip) >= 90:
     if abs(dip) >= 90:
-	grass.fatal(_("dip must be between -90 and 90."))
+        gscript.fatal(_("dip must be between -90 and 90."))
 
 
     if az < 0 or az >= 360:
     if az < 0 or az >= 360:
-	grass.fatal(_("azimuth must be between 0 and 360"))
+        gscript.fatal(_("azimuth must be between 0 and 360"))
 
 
-    ### now the actual algorithm
-    az_r  = math.radians(-az)
+    # now the actual algorithm
+    az_r = math.radians(-az)
     sinaz = math.sin(az_r)
     sinaz = math.sin(az_r)
     cosaz = math.cos(az_r)
     cosaz = math.cos(az_r)
 
 
@@ -102,27 +101,28 @@ def main():
     kz = el - ea * sinaz * tandip - no * cosaz * tandip
     kz = el - ea * sinaz * tandip - no * cosaz * tandip
 
 
     if type == "CELL":
     if type == "CELL":
-	round = "round"
-	dtype = "int"
+        round = "round"
+        dtype = "int"
     elif type == "FCELL":
     elif type == "FCELL":
-	round = ""
-	dtype = "float"
+        round = ""
+        dtype = "float"
     else:
     else:
-	round = ""
-	dtype = "double"
+        round = ""
+        dtype = "double"
 
 
-    grass.mapcalc("$name = $type($round(x() * $kx + y() * $ky + $kz))",
-		  name = name, type = dtype, round = round, kx = kx, ky = ky, kz = kz)
+    gscript.mapcalc("$name = $type($round(x() * $kx + y() * $ky + $kz))",
+                    name=name, type=dtype, round=round, kx=kx, ky=ky, kz=kz)
 
 
-    grass.run_command('r.support', map = name, history = '')
-    grass.raster_history(name)
+    gscript.run_command('r.support', map=name, history='')
+    gscript.raster_history(name)
 
 
-    grass.message(_("Done."))
-    t = string.Template("Raster map <$name> generated by r.plane " +
-			"at point $ea E, $no N, elevation $el with dip = $dip degrees and " +
-			"aspect = $az degrees ccw from north.")
-    grass.message(t.substitute(name = name, ea = ea, no = no, el = el, dip = dip, az = az))
+    gscript.message(_("Done."))
+    t = string.Template("Raster map <$name> generated by r.plane "
+                        "at point $ea E, $no N, elevation $el with dip = $dip"
+                        " degrees and aspect = $az degrees ccw from north.")
+    gscript.message(t.substitute(name=name, ea=ea, no=no, el=el, dip=dip,
+                                 az=az))
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     main()
     main()

+ 1 - 1
scripts/r.reclass.area/r.reclass.area.py

@@ -204,7 +204,7 @@ def main():
     limit = float(value)
     limit = float(value)
     if mode == 'greater' and method == 'rmarea':
     if mode == 'greater' and method == 'rmarea':
         grass.fatal(_("You have to specify mode='lesser' with method='rmarea'"))
         grass.fatal(_("You have to specify mode='lesser' with method='rmarea'"))
-    
+
     if not grass.find_file(infile)['name']:
     if not grass.find_file(infile)['name']:
         grass.fatal(_("Raster map <%s> not found") % infile)
         grass.fatal(_("Raster map <%s> not found") % infile)
 
 

+ 5 - 3
scripts/r.shade/r.shade.py

@@ -111,15 +111,17 @@ def main():
             relief_map = relief_map_tmp
             relief_map = relief_map_tmp
             to_remove.append(relief_map_tmp)
             to_remove.append(relief_map_tmp)
         gcore.run_command('r.his', hue=drape_map, intensity=relief_map,
         gcore.run_command('r.his', hue=drape_map, intensity=relief_map,
-                          red=tmp_r, green=tmp_g, blue=tmp_b, **rhis_extra_args)
+                          red=tmp_r, green=tmp_g, blue=tmp_b,
+                          **rhis_extra_args)
         to_remove.extend([tmp_r, tmp_g, tmp_b])
         to_remove.extend([tmp_r, tmp_g, tmp_b])
         gcore.run_command('r.composite', red=tmp_r, green=tmp_g,
         gcore.run_command('r.composite', red=tmp_r, green=tmp_g,
                           blue=tmp_b, output=output_map)
                           blue=tmp_b, output=output_map)
         remove(to_remove)  # who knows if finally is called when exit
         remove(to_remove)  # who knows if finally is called when exit
-    except CalledModuleError, error:
+    except CalledModuleError as error:
         remove(to_remove)
         remove(to_remove)
         # TODO: implement module name to CalledModuleError
         # TODO: implement module name to CalledModuleError
-        gcore.fatal(_("Module %s failed. Check the above error messages.") % error.cmd)
+        gcore.fatal(_("Module %s failed. Check the above error messages.") %
+                    error.cmd)
 
 
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":

+ 48 - 38
scripts/r.tileset/r.tileset.py

@@ -106,13 +106,14 @@
 # An array of points indexed by 0 for "x" and 4 for "y" + by number 0, 1, 2, and 3
 # An array of points indexed by 0 for "x" and 4 for "y" + by number 0, 1, 2, and 3
 # A reprojector [0] is name of source projection, [1] is name of destination
 # A reprojector [0] is name of source projection, [1] is name of destination
 # A projection - [0] is proj.4 text, [1] is scale
 # A projection - [0] is proj.4 text, [1] is scale
+from __future__ import print_function
 
 
 import sys
 import sys
 import tempfile
 import tempfile
 import math
 import math
 
 
 from grass.script.utils import separator
 from grass.script.utils import separator
-from grass.script import core as grass
+from grass.script import core as gcore
 from grass.exceptions import CalledModuleError
 from grass.exceptions import CalledModuleError
 
 
 
 
@@ -158,7 +159,7 @@ def project(file, source, dest):
     errors = 0
     errors = 0
     points = []
     points = []
     try:
     try:
-        ret = grass.read_command('m.proj',
+        ret = gcore.read_command('m.proj',
                                  quiet=True,
                                  quiet=True,
                                  flags='d',
                                  flags='d',
                                  proj_in=source['proj'],
                                  proj_in=source['proj'],
@@ -166,10 +167,10 @@ def project(file, source, dest):
                                  sep=';',
                                  sep=';',
                                  input=file)
                                  input=file)
     except CalledModuleError:
     except CalledModuleError:
-        grass.fatal(cs2cs + ' failed')
+        gcore.fatal(cs2cs + ' failed')
 
 
     if not ret:
     if not ret:
-        grass.fatal(cs2cs + ' failed')
+        gcore.fatal(cs2cs + ' failed')
 
 
     for line in ret.splitlines():
     for line in ret.splitlines():
         if "*" in line:
         if "*" in line:
@@ -238,40 +239,42 @@ def main():
     max_rows = int(options['maxrows']) - int(options['overlap'])
     max_rows = int(options['maxrows']) - int(options['overlap'])
 
 
     if max_cols == 0:
     if max_cols == 0:
-        grass.fatal(_("It is not possibile to set 'maxcols=%s' and "
+        gcore.fatal(_("It is not possibile to set 'maxcols=%s' and "
                       "'overlap=%s'. Please set maxcols>overlap" %
                       "'overlap=%s'. Please set maxcols>overlap" %
                       (options['maxcols'], options['overlap'])))
                       (options['maxcols'], options['overlap'])))
     elif max_rows == 0:
     elif max_rows == 0:
-        grass.fatal(_("It is not possibile to set 'maxrows=%s' and "
+        gcore.fatal(_("It is not possibile to set 'maxrows=%s' and "
                       "'overlap=%s'. Please set maxrows>overlap" %
                       "'overlap=%s'. Please set maxrows>overlap" %
                       (options['maxrows'], options['overlap'])))
                       (options['maxrows'], options['overlap'])))
     # destination projection
     # destination projection
     if not options['destproj']:
     if not options['destproj']:
-        dest_proj = grass.read_command('g.proj',
+        dest_proj = gcore.read_command('g.proj',
                                        quiet=True,
                                        quiet=True,
                                        flags='jf').rstrip('\n')
                                        flags='jf').rstrip('\n')
         if not dest_proj:
         if not dest_proj:
-            grass.fatal(_('g.proj failed'))
+            gcore.fatal(_('g.proj failed'))
     else:
     else:
         dest_proj = options['destproj']
         dest_proj = options['destproj']
-    grass.debug("Getting destination projection -> '%s'" % dest_proj)
+    gcore.debug("Getting destination projection -> '%s'" % dest_proj)
 
 
     # projection scale
     # projection scale
     if not options['destscale']:
     if not options['destscale']:
-        ret = grass.parse_command('g.proj',
+        ret = gcore.parse_command('g.proj',
                                   quiet=True,
                                   quiet=True,
                                   flags='j')
                                   flags='j')
         if not ret:
         if not ret:
-            grass.fatal(_('g.proj failed'))
+            gcore.fatal(_('g.proj failed'))
 
 
         if '+to_meter' in ret:
         if '+to_meter' in ret:
             dest_scale = ret['+to_meter'].strip()
             dest_scale = ret['+to_meter'].strip()
         else:
         else:
-            grass.warning(_("Scale (%s) not found, assuming '1'") % '+to_meter')
+            gcore.warning(
+                _("Scale (%s) not found, assuming '1'") %
+                '+to_meter')
             dest_scale = '1'
             dest_scale = '1'
     else:
     else:
         dest_scale = options['destscale']
         dest_scale = options['destscale']
-    grass.debug('Getting destination projection scale -> %s' % dest_scale)
+    gcore.debug('Getting destination projection scale -> %s' % dest_scale)
 
 
     # set up the projections
     # set up the projections
     srs_source = {'proj': options['sourceproj'],
     srs_source = {'proj': options['sourceproj'],
@@ -279,17 +282,17 @@ def main():
     srs_dest = {'proj': dest_proj, 'scale': float(dest_scale)}
     srs_dest = {'proj': dest_proj, 'scale': float(dest_scale)}
 
 
     if options['region']:
     if options['region']:
-        grass.run_command('g.region',
+        gcore.run_command('g.region',
                           quiet=True,
                           quiet=True,
                           region=options['region'])
                           region=options['region'])
-    dest_bbox = grass.region()
-    grass.debug('Getting destination region')
+    dest_bbox = gcore.region()
+    gcore.debug('Getting destination region')
 
 
     # output field separator
     # output field separator
     fs = separator(options['separator'])
     fs = separator(options['separator'])
 
 
     # project the destination region into the source:
     # project the destination region into the source:
-    grass.verbose('Projecting destination region into source...')
+    gcore.verbose('Projecting destination region into source...')
     dest_bbox_points = bboxToPoints(dest_bbox)
     dest_bbox_points = bboxToPoints(dest_bbox)
 
 
     dest_bbox_source_points, errors_dest = projectPoints(dest_bbox_points,
     dest_bbox_source_points, errors_dest = projectPoints(dest_bbox_points,
@@ -297,24 +300,24 @@ def main():
                                                          dest=srs_source)
                                                          dest=srs_source)
 
 
     if len(dest_bbox_source_points) == 0:
     if len(dest_bbox_source_points) == 0:
-        grass.fatal(_("There are no tiles available. Probably the output "
+        gcore.fatal(_("There are no tiles available. Probably the output "
                       "projection system it is not compatible with the "
                       "projection system it is not compatible with the "
                       "projection of the current location"))
                       "projection of the current location"))
 
 
     source_bbox = pointsToBbox(dest_bbox_source_points)
     source_bbox = pointsToBbox(dest_bbox_source_points)
 
 
-    grass.verbose('Projecting source bounding box into destination...')
+    gcore.verbose('Projecting source bounding box into destination...')
 
 
     source_bbox_points = bboxToPoints(source_bbox)
     source_bbox_points = bboxToPoints(source_bbox)
 
 
     source_bbox_dest_points, errors_source = projectPoints(source_bbox_points,
     source_bbox_dest_points, errors_source = projectPoints(source_bbox_points,
-                                                            source=srs_source,
-                                                            dest=srs_dest)
+                                                           source=srs_source,
+                                                           dest=srs_dest)
 
 
     x_metric = 1 / dest_bbox['ewres']
     x_metric = 1 / dest_bbox['ewres']
     y_metric = 1 / dest_bbox['nsres']
     y_metric = 1 / dest_bbox['nsres']
 
 
-    grass.verbose('Computing length of sides of source bounding box...')
+    gcore.verbose('Computing length of sides of source bounding box...')
 
 
     source_bbox_dest_lengths = sideLengths(source_bbox_dest_points,
     source_bbox_dest_lengths = sideLengths(source_bbox_dest_points,
                                            x_metric, y_metric)
                                            x_metric, y_metric)
@@ -324,12 +327,14 @@ def main():
     # In the direction (x or y) in which the world is least skewed (ie north south in lat long)
     # In the direction (x or y) in which the world is least skewed (ie north south in lat long)
     # Divide the world into strips. These strips are as big as possible contrained by max_
     # Divide the world into strips. These strips are as big as possible contrained by max_
     # In the other direction do the same thing.
     # In the other direction do the same thing.
-    # Theres some recomputation of the size of the world that's got to come in here somewhere.
+    # Theres some recomputation of the size of the world that's got to come in
+    # here somewhere.
 
 
     # For now, however, we are going to go ahead and request more data than is necessary.
     # For now, however, we are going to go ahead and request more data than is necessary.
     # For small regions far from the critical areas of projections this makes very little difference
     # For small regions far from the critical areas of projections this makes very little difference
     # in the amount of data gotten.
     # in the amount of data gotten.
-    # We can make this efficient for big regions or regions near critical points later.
+    # We can make this efficient for big regions or regions near critical
+    # points later.
 
 
     bigger = []
     bigger = []
     bigger.append(max(source_bbox_dest_lengths['x']))
     bigger.append(max(source_bbox_dest_lengths['x']))
@@ -342,7 +347,7 @@ def main():
     # I'm going to make the numbers all simpler and add this extra cell to
     # I'm going to make the numbers all simpler and add this extra cell to
     # every tile.
     # every tile.
 
 
-    grass.message(_('Computing tiling...'))
+    gcore.message(_('Computing tiling...'))
     tiles = [-1, -1]
     tiles = [-1, -1]
     tile_base_size = [-1, -1]
     tile_base_size = [-1, -1]
     tiles_extra_1 = [-1, -1]
     tiles_extra_1 = [-1, -1]
@@ -363,7 +368,7 @@ def main():
         # Add overlap to tiles (doesn't effect tileset_size
         # Add overlap to tiles (doesn't effect tileset_size
         tile_size_overlap[i] = tile_size[i] + int(options['overlap'])
         tile_size_overlap[i] = tile_size[i] + int(options['overlap'])
 
 
-    grass.verbose("There will be %d by %d tiles each %d by %d cells" %
+    gcore.verbose("There will be %d by %d tiles each %d by %d cells" %
                   (tiles[0], tiles[1], tile_size[0], tile_size[1]))
                   (tiles[0], tiles[1], tile_size[0], tile_size[1]))
 
 
     ximax = tiles[0]
     ximax = tiles[0]
@@ -380,16 +385,21 @@ def main():
     tile_bbox = {'w': -1, 's': -1, 'e': -1, 'n': -1}
     tile_bbox = {'w': -1, 's': -1, 'e': -1, 'n': -1}
 
 
     if errors_dest > 0:
     if errors_dest > 0:
-        grass.warning(_("During computation %i tiles could not be created" %
+        gcore.warning(_("During computation %i tiles could not be created" %
                         errors_dest))
                         errors_dest))
 
 
     while xi < ximax:
     while xi < ximax:
-        tile_bbox['w'] = float(min_x) + (float(xi) * float(tile_size[0]) / float(tileset_size[0])) * float(span_x)
-        tile_bbox['e'] = float(min_x) + (float(xi + 1) * float(tile_size_overlap[0]) / float(tileset_size[0])) * float(span_x)
+        tile_bbox['w'] = float(
+            min_x) + (float(xi) * float(tile_size[0]) / float(tileset_size[0])) * float(span_x)
+        tile_bbox['e'] = float(min_x) + (float(xi + 1) * float(tile_size_overlap[0]
+                                                               ) / float(tileset_size[0])) * float(span_x)
         yi = 0
         yi = 0
         while yi < yimax:
         while yi < yimax:
-            tile_bbox['s'] = float(min_y) + (float(yi) * float(tile_size[1]) / float(tileset_size[1])) * float(span_y)
-            tile_bbox['n'] = float(min_y) + (float(yi + 1) * float(tile_size_overlap[1]) / float(tileset_size[1])) * float(span_y)
+            tile_bbox['s'] = float(
+                min_y) + (float(yi) * float(tile_size[1]) / float(tileset_size[1])) * float(span_y)
+            tile_bbox['n'] = float(min_y) + (
+                float(yi + 1) * float(tile_size_overlap[1]) /
+                float(tileset_size[1])) * float(span_y)
             tile_bbox_points = bboxToPoints(tile_bbox)
             tile_bbox_points = bboxToPoints(tile_bbox)
             tile_dest_bbox_points, errors = projectPoints(tile_bbox_points,
             tile_dest_bbox_points, errors = projectPoints(tile_bbox_points,
                                                           source=srs_source,
                                                           source=srs_source,
@@ -397,24 +407,24 @@ def main():
             tile_dest_bbox = pointsToBbox(tile_dest_bbox_points)
             tile_dest_bbox = pointsToBbox(tile_dest_bbox_points)
             if bboxesIntersect(tile_dest_bbox, dest_bbox):
             if bboxesIntersect(tile_dest_bbox, dest_bbox):
                 if flags['w']:
                 if flags['w']:
-                    print "bbox=%s,%s,%s,%s&width=%s&height=%s" % \
+                    print("bbox=%s,%s,%s,%s&width=%s&height=%s" %
                           (tile_bbox['w'], tile_bbox['s'], tile_bbox['e'],
                           (tile_bbox['w'], tile_bbox['s'], tile_bbox['e'],
                            tile_bbox['n'], tile_size_overlap[0],
                            tile_bbox['n'], tile_size_overlap[0],
-                           tile_size_overlap[1])
+                           tile_size_overlap[1]))
                 elif flags['g']:
                 elif flags['g']:
-                    print "w=%s;s=%s;e=%s;n=%s;cols=%s;rows=%s" % \
+                    print("w=%s;s=%s;e=%s;n=%s;cols=%s;rows=%s" %
                           (tile_bbox['w'], tile_bbox['s'], tile_bbox['e'],
                           (tile_bbox['w'], tile_bbox['s'], tile_bbox['e'],
                            tile_bbox['n'], tile_size_overlap[0],
                            tile_bbox['n'], tile_size_overlap[0],
-                           tile_size_overlap[1])
+                           tile_size_overlap[1]))
                 else:
                 else:
-                    print "%s%s%s%s%s%s%s%s%s%s%s" % \
+                    print("%s%s%s%s%s%s%s%s%s%s%s" %
                           (tile_bbox['w'], fs, tile_bbox['s'], fs,
                           (tile_bbox['w'], fs, tile_bbox['s'], fs,
                            tile_bbox['e'], fs, tile_bbox['n'], fs,
                            tile_bbox['e'], fs, tile_bbox['n'], fs,
-                           tile_size_overlap[0], fs, tile_size_overlap[1])
+                           tile_size_overlap[0], fs, tile_size_overlap[1]))
             yi += 1
             yi += 1
         xi += 1
         xi += 1
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
     cs2cs = 'cs2cs'
     cs2cs = 'cs2cs'
-    options, flags = grass.parser()
+    options, flags = gcore.parser()
     sys.exit(main())
     sys.exit(main())

+ 13 - 11
scripts/r.unpack/r.unpack.py

@@ -82,7 +82,8 @@ def main():
         if os.environ.get('GRASS_OVERWRITE', '0') != '1':
         if os.environ.get('GRASS_OVERWRITE', '0') != '1':
             grass.fatal(_('Raster map <{name}> already exists'.format(name=map_name)))
             grass.fatal(_('Raster map <{name}> already exists'.format(name=map_name)))
         else:
         else:
-            grass.warning(_('Raster map <{name}> already exists and will be overwritten'.format(name=map_name)))
+            grass.warning(
+                _('Raster map <{name}> already exists and will be overwritten'.format(name=map_name)))
 
 
     # extract data
     # extract data
     tar.extractall()
     tar.extractall()
@@ -100,36 +101,37 @@ def main():
 
 
     if flags['o']:
     if flags['o']:
         grass.warning(_("Overriding projection check (using current location's projection)."))
         grass.warning(_("Overriding projection check (using current location's projection)."))
-        
+
     else:
     else:
-        
+
         diff_result_1 = diff_result_2 = None
         diff_result_1 = diff_result_2 = None
-        
+
         proj_info_file_1 = 'PROJ_INFO'
         proj_info_file_1 = 'PROJ_INFO'
         proj_info_file_2 = os.path.join(mset_dir, '..', 'PERMANENT', 'PROJ_INFO')
         proj_info_file_2 = os.path.join(mset_dir, '..', 'PERMANENT', 'PROJ_INFO')
 
 
         skip_projection_check = False
         skip_projection_check = False
         if not os.path.exists(proj_info_file_1):
         if not os.path.exists(proj_info_file_1):
             if os.path.exists(proj_info_file_2):
             if os.path.exists(proj_info_file_2):
-                grass.fatal(_("PROJ_INFO file is missing, unpack raster map in XY (unprojected) location."))
+                grass.fatal(
+                    _("PROJ_INFO file is missing, unpack raster map in XY (unprojected) location."))
             skip_projection_check = True  # XY location
             skip_projection_check = True  # XY location
 
 
         if not skip_projection_check:
         if not skip_projection_check:
             if not grass.compare_key_value_text_files(filename_a=proj_info_file_1,
             if not grass.compare_key_value_text_files(filename_a=proj_info_file_1,
                                                       filename_b=proj_info_file_2,
                                                       filename_b=proj_info_file_2,
-                                                      proj=True):                                                      
+                                                      proj=True):
                 diff_result_1 = diff_files(proj_info_file_1, proj_info_file_2)
                 diff_result_1 = diff_files(proj_info_file_1, proj_info_file_2)
-        
+
             proj_units_file_1 = 'PROJ_UNITS'
             proj_units_file_1 = 'PROJ_UNITS'
             proj_units_file_2 = os.path.join(mset_dir, '..', 'PERMANENT', 'PROJ_UNITS')
             proj_units_file_2 = os.path.join(mset_dir, '..', 'PERMANENT', 'PROJ_UNITS')
-        
+
             if not grass.compare_key_value_text_files(filename_a=proj_units_file_1,
             if not grass.compare_key_value_text_files(filename_a=proj_units_file_1,
                                                       filename_b=proj_units_file_2,
                                                       filename_b=proj_units_file_2,
-                                                      units=True):                                                      
+                                                      units=True):
                 diff_result_2 = diff_files(proj_units_file_1, proj_units_file_2)
                 diff_result_2 = diff_files(proj_units_file_1, proj_units_file_2)
-        
+
             if diff_result_1 or diff_result_2:
             if diff_result_1 or diff_result_2:
-                
+
                 if diff_result_1:
                 if diff_result_1:
                     grass.warning(_("Difference between PROJ_INFO file of packed map "
                     grass.warning(_("Difference between PROJ_INFO file of packed map "
                                     "and of current location:\n{diff}").format(diff=''.join(diff_result_1)))
                                     "and of current location:\n{diff}").format(diff=''.join(diff_result_1)))

+ 2 - 2
scripts/r3.in.xyz/r3.in.xyz.py

@@ -280,7 +280,7 @@ def main():
                                       **addl_opts)
                                       **addl_opts)
 
 
         grass.debug("i=%d, %%=%d  (workers=%d)" % (i, i % workers, workers))
         grass.debug("i=%d, %%=%d  (workers=%d)" % (i, i % workers, workers))
-        #print sys.getsizeof(proc)  # sizeof(proc array)  [not so big]
+        # print sys.getsizeof(proc)  # sizeof(proc array)  [not so big]
 
 
         if i % workers is 0:
         if i % workers is 0:
             # wait for the ones launched so far to finish
             # wait for the ones launched so far to finish
@@ -299,7 +299,7 @@ def main():
 
 
     grass.verbose(_("Assembling 3D cube ..."))
     grass.verbose(_("Assembling 3D cube ..."))
 
 
-    #input order: lower most strata first
+    # input order: lower most strata first
     slices = grass.read_command('g.list', type='raster', sep=',',
     slices = grass.read_command('g.list', type='raster', sep=',',
                                 pattern='tmp.r3xyz.%d.*' % os.getpid()).rstrip(os.linesep)
                                 pattern='tmp.r3xyz.%d.*' % os.getpid()).rstrip(os.linesep)
     grass.debug(slices)
     grass.debug(slices)

+ 5 - 4
scripts/v.build.all/v.build.all.py

@@ -22,6 +22,7 @@ import sys
 from grass.script import core as grass
 from grass.script import core as grass
 from grass.exceptions import CalledModuleError
 from grass.exceptions import CalledModuleError
 
 
+
 def main():
 def main():
     env = grass.gisenv()
     env = grass.gisenv()
     mapset = env['MAPSET']
     mapset = env['MAPSET']
@@ -29,17 +30,17 @@ def main():
 
 
     vectors = grass.list_grouped('vect')[mapset]
     vectors = grass.list_grouped('vect')[mapset]
     num_vectors = len(vectors)
     num_vectors = len(vectors)
-    
+
     if grass.verbosity() < 2:
     if grass.verbosity() < 2:
         quiet = True
         quiet = True
     else:
     else:
         quiet = False
         quiet = False
-        
+
     i = 1
     i = 1
     for vect in vectors:
     for vect in vectors:
         map = "%s@%s" % (vect, mapset)
         map = "%s@%s" % (vect, mapset)
-        grass.message(_("%s\nBuilding topology for vector map <%s> (%d of %d)...\n%s") % \
-                          ('-' * 80, map, i, num_vectors, '-' * 80))
+        grass.message(_("%s\nBuilding topology for vector map <%s> (%d of %d)...\n%s") %
+                      ('-' * 80, map, i, num_vectors, '-' * 80))
         grass.verbose(_("v.build map=%s") % map)
         grass.verbose(_("v.build map=%s") % map)
         try:
         try:
             grass.run_command("v.build", map=map, quiet=quiet)
             grass.run_command("v.build", map=map, quiet=quiet)

+ 7 - 8
scripts/v.centroids/v.centroids.py

@@ -50,20 +50,19 @@
 #%end
 #%end
 
 
 import sys
 import sys
-import os
-import re
-import grass.script as grass
+import grass.script as gscript
+
 
 
 def main():
 def main():
     if options['option'] == 'add':
     if options['option'] == 'add':
-        num_bound = grass.vector_info_topo(map = options['input'])['boundaries']
-	if num_bound == 0:
-	    grass.fatal(_("Input vector map contains no boundaries."))
+        num_bound = gscript.vector_info_topo(map=options['input'])['boundaries']
+        if num_bound == 0:
+            gscript.fatal(_("Input vector map contains no boundaries."))
 
 
-	grass.exec_command("v.category", type = 'area', **options)
+        gscript.exec_command("v.category", type='area', **options)
 
 
     sys.exit(0)
     sys.exit(0)
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     main()
     main()

+ 17 - 15
scripts/v.db.addcolumn/v.db.addcolumn.py

@@ -3,7 +3,7 @@
 ############################################################################
 ############################################################################
 #
 #
 # MODULE:       v.db.addcolumnumn
 # MODULE:       v.db.addcolumnumn
-# AUTHOR(S):    Moritz Lennert 
+# AUTHOR(S):    Moritz Lennert
 #               Converted to Python by Glynn Clements
 #               Converted to Python by Glynn Clements
 # PURPOSE:      interface to db.execute to add a column to the attribute table
 # PURPOSE:      interface to db.execute to add a column to the attribute table
 #               connected to a given vector map
 #               connected to a given vector map
@@ -42,29 +42,31 @@ import sys
 import os
 import os
 import grass.script as grass
 import grass.script as grass
 
 
+
 def main():
 def main():
-    map     = options['map']
-    layer   = options['layer']
+    map = options['map']
+    layer = options['layer']
     columns = options['columns']
     columns = options['columns']
     columns = [col.strip() for col in columns.split(',')]
     columns = [col.strip() for col in columns.split(',')]
-    
+
     # does map exist in CURRENT mapset?
     # does map exist in CURRENT mapset?
     mapset = grass.gisenv()['MAPSET']
     mapset = grass.gisenv()['MAPSET']
-    exists = bool(grass.find_file(map, element = 'vector', mapset = mapset)['file'])
-    
+    exists = bool(grass.find_file(map, element='vector', mapset=mapset)['file'])
+
     if not exists:
     if not exists:
         grass.fatal(_("Vector map <%s> not found in current mapset") % map)
         grass.fatal(_("Vector map <%s> not found in current mapset") % map)
-    
+
     try:
     try:
         f = grass.vector_db(map)[int(layer)]
         f = grass.vector_db(map)[int(layer)]
     except KeyError:
     except KeyError:
-        grass.fatal(_("There is no table connected to this map. Run v.db.connect or v.db.addtable first."))
-    
-    table    = f['table']
+        grass.fatal(
+            _("There is no table connected to this map. Run v.db.connect or v.db.addtable first."))
+
+    table = f['table']
     database = f['database']
     database = f['database']
-    driver   = f['driver']
-    column_existing = grass.vector_columns(map, int(layer)).keys()    
-    
+    driver = f['driver']
+    column_existing = grass.vector_columns(map, int(layer)).keys()
+
     for col in columns:
     for col in columns:
         if not col:
         if not col:
             grass.fatal(_("There is an empty column. Did you leave a trailing comma?"))
             grass.fatal(_("There is an empty column. Did you leave a trailing comma?"))
@@ -73,13 +75,13 @@ def main():
             grass.error(_("Column <%s> is already in the table. Skipping.") % col_name)
             grass.error(_("Column <%s> is already in the table. Skipping.") % col_name)
             continue
             continue
         grass.verbose(_("Adding column <%s> to the table") % col_name)
         grass.verbose(_("Adding column <%s> to the table") % col_name)
-        p = grass.feed_command('db.execute', input = '-', database = database, driver = driver)
+        p = grass.feed_command('db.execute', input='-', database=database, driver=driver)
         p.stdin.write("ALTER TABLE %s ADD COLUMN %s" % (table, col))
         p.stdin.write("ALTER TABLE %s ADD COLUMN %s" % (table, col))
         grass.debug("ALTER TABLE %s ADD COLUMN %s" % (table, col))
         grass.debug("ALTER TABLE %s ADD COLUMN %s" % (table, col))
         p.stdin.close()
         p.stdin.close()
         if p.wait() != 0:
         if p.wait() != 0:
             grass.fatal(_("Unable to add column <%s>.") % col)
             grass.fatal(_("Unable to add column <%s>.") % col)
-    
+
     # write cmd history:
     # write cmd history:
     grass.vector_history(map)
     grass.vector_history(map)
 
 

+ 31 - 29
scripts/v.db.addtable/v.db.addtable.py

@@ -3,7 +3,7 @@
 ############################################################################
 ############################################################################
 #
 #
 # MODULE:       v.db.addtable
 # MODULE:       v.db.addtable
-# AUTHOR(S):    Markus Neteler 
+# AUTHOR(S):    Markus Neteler
 #               Converted to Python by Glynn Clements
 #               Converted to Python by Glynn Clements
 #               Key column added by Martin Landa <landa.martin gmail.com>
 #               Key column added by Martin Landa <landa.martin gmail.com>
 # PURPOSE:      interface to db.execute to creates and add a new table to given vector map
 # PURPOSE:      interface to db.execute to creates and add a new table to given vector map
@@ -23,14 +23,14 @@
 #%end
 #%end
 #%option G_OPT_V_MAP
 #%option G_OPT_V_MAP
 #%end
 #%end
-#%option 
+#%option
 #% key: table
 #% key: table
 #% type: string
 #% type: string
 #% description: Name of new attribute table (default: vector map name)
 #% description: Name of new attribute table (default: vector map name)
 #% required: no
 #% required: no
 #% guisection: Definition
 #% guisection: Definition
 #%end
 #%end
-#%option 
+#%option
 #% key: layer
 #% key: layer
 #% type: integer
 #% type: integer
 #% description: Layer number where to add new attribute table
 #% description: Layer number where to add new attribute table
@@ -64,14 +64,14 @@ def main():
     layer = options['layer']
     layer = options['layer']
     columns = options['columns']
     columns = options['columns']
     key = options['key']
     key = options['key']
-    
+
     # does map exist in CURRENT mapset?
     # does map exist in CURRENT mapset?
     mapset = grass.gisenv()['MAPSET']
     mapset = grass.gisenv()['MAPSET']
-    if not grass.find_file(vector, element = 'vector', mapset = mapset)['file']:
+    if not grass.find_file(vector, element='vector', mapset=mapset)['file']:
         grass.fatal(_("Vector map <%s> not found in current mapset") % vector)
         grass.fatal(_("Vector map <%s> not found in current mapset") % vector)
-    
+
     map_name = vector.split('@')[0]
     map_name = vector.split('@')[0]
-    
+
     if not table:
     if not table:
         if layer == '1':
         if layer == '1':
             grass.verbose(_("Using vector map name as table name: <%s>") % map_name)
             grass.verbose(_("Using vector map name as table name: <%s>") % map_name)
@@ -79,44 +79,46 @@ def main():
         else:
         else:
             # to avoid tables with identical names on higher layers
             # to avoid tables with identical names on higher layers
             table = "%s_%s" % (map_name, layer)
             table = "%s_%s" % (map_name, layer)
-            grass.verbose(_("Using vector map name extended by layer number as table name: <%s>") % table)
+            grass.verbose(
+                _("Using vector map name extended by layer number as table name: <%s>") %
+                table)
     else:
     else:
         grass.verbose(_("Using user specified table name: %s") % table)
         grass.verbose(_("Using user specified table name: %s") % table)
-    
+
     # check if DB parameters are set, and if not set them.
     # check if DB parameters are set, and if not set them.
-    grass.run_command('db.connect', flags = 'c')
+    grass.run_command('db.connect', flags='c')
     grass.verbose(_("Creating new DB connection based on default mapset settings..."))
     grass.verbose(_("Creating new DB connection based on default mapset settings..."))
     kv = grass.db_connection()
     kv = grass.db_connection()
     database = kv['database']
     database = kv['database']
     driver = kv['driver']
     driver = kv['driver']
     schema = kv['schema']
     schema = kv['schema']
-    
+
     # maybe there is already a table linked to the selected layer?
     # maybe there is already a table linked to the selected layer?
     nuldev = file(os.devnull, 'w')
     nuldev = file(os.devnull, 'w')
     try:
     try:
-        grass.vector_db(map_name, stderr = nuldev)[int(layer)]
+        grass.vector_db(map_name, stderr=nuldev)[int(layer)]
         grass.fatal(_("There is already a table linked to layer <%s>") % layer)
         grass.fatal(_("There is already a table linked to layer <%s>") % layer)
     except KeyError:
     except KeyError:
         pass
         pass
-    
+
     # maybe there is already a table with that name?
     # maybe there is already a table with that name?
-    tables = grass.read_command('db.tables', flags = 'p', database = database, driver = driver,
-                                stderr = nuldev)
-    
+    tables = grass.read_command('db.tables', flags='p', database=database, driver=driver,
+                                stderr=nuldev)
+
     if not table in tables.splitlines():
     if not table in tables.splitlines():
         if columns:
         if columns:
             column_def = map(lambda x: x.strip().lower(), columns.strip().split(','))
             column_def = map(lambda x: x.strip().lower(), columns.strip().split(','))
         else:
         else:
             column_def = []
             column_def = []
-        
+
         # if not existing, create it:
         # if not existing, create it:
         column_def_key = "%s integer" % key
         column_def_key = "%s integer" % key
         if column_def_key not in column_def:
         if column_def_key not in column_def:
             column_def.insert(0, column_def_key)
             column_def.insert(0, column_def_key)
         column_def = ','.join(column_def)
         column_def = ','.join(column_def)
-        
+
         grass.verbose(_("Creating table with columns (%s)...") % column_def)
         grass.verbose(_("Creating table with columns (%s)...") % column_def)
-        
+
         sql = "CREATE TABLE %s (%s)" % (table, column_def)
         sql = "CREATE TABLE %s (%s)" % (table, column_def)
         try:
         try:
             grass.run_command('db.execute',
             grass.run_command('db.execute',
@@ -127,22 +129,22 @@ def main():
     # connect the map to the DB:
     # connect the map to the DB:
     if schema:
     if schema:
         table = '{schema}.{table}'.format(schema=schema, table=table)
         table = '{schema}.{table}'.format(schema=schema, table=table)
-    grass.run_command('v.db.connect', quiet = True,
-                      map = map_name, database = database, driver = driver,
-                      layer = layer, table = table, key = key)
-    
+    grass.run_command('v.db.connect', quiet=True,
+                      map=map_name, database=database, driver=driver,
+                      layer=layer, table=table, key=key)
+
     # finally we have to add cats into the attribute DB to make modules such as v.what.rast happy:
     # finally we have to add cats into the attribute DB to make modules such as v.what.rast happy:
     # (creates new row for each vector line):
     # (creates new row for each vector line):
-    grass.run_command('v.to.db', map = map_name, layer = layer,
-                      option = 'cat', column = key, qlayer = layer)
-    
+    grass.run_command('v.to.db', map=map_name, layer=layer,
+                      option='cat', column=key, qlayer=layer)
+
     grass.verbose(_("Current attribute table links:"))
     grass.verbose(_("Current attribute table links:"))
     if grass.verbosity() > 2:
     if grass.verbosity() > 2:
-        grass.run_command('v.db.connect', flags = 'p', map = map_name)
-    
+        grass.run_command('v.db.connect', flags='p', map=map_name)
+
     # write cmd history:
     # write cmd history:
     grass.vector_history(map_name)
     grass.vector_history(map_name)
-    
+
     return 0
     return 0
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":

+ 22 - 22
scripts/v.db.dropcolumn/v.db.dropcolumn.py

@@ -5,7 +5,7 @@
 # MODULE:       v.db.dropcolumn
 # MODULE:       v.db.dropcolumn
 # AUTHOR(S):    Markus Neteler
 # AUTHOR(S):    Markus Neteler
 #               Converted to Python by Glynn Clements
 #               Converted to Python by Glynn Clements
-# PURPOSE:      interface to db.execute to drop a column from the 
+# PURPOSE:      interface to db.execute to drop a column from the
 #               attribute table connected to a given vector map
 #               attribute table connected to a given vector map
 #               - Based on v.db.addcolumn
 #               - Based on v.db.addcolumn
 #               - with special trick for SQLite
 #               - with special trick for SQLite
@@ -45,43 +45,43 @@ from grass.exceptions import CalledModuleError
 
 
 
 
 def main():
 def main():
-    map    = options['map']
-    layer  = options['layer']
+    map = options['map']
+    layer = options['layer']
     columns = options['columns'].split(',')
     columns = options['columns'].split(',')
-    
+
     mapset = grass.gisenv()['MAPSET']
     mapset = grass.gisenv()['MAPSET']
-    
+
     # does map exist in CURRENT mapset?
     # does map exist in CURRENT mapset?
-    if not grass.find_file(map, element = 'vector', mapset = mapset)['file']:
+    if not grass.find_file(map, element='vector', mapset=mapset)['file']:
         grass.fatal(_("Vector map <%s> not found in current mapset") % map)
         grass.fatal(_("Vector map <%s> not found in current mapset") % map)
-    
+
     f = grass.vector_layer_db(map, layer)
     f = grass.vector_layer_db(map, layer)
-    
+
     table = f['table']
     table = f['table']
     keycol = f['key']
     keycol = f['key']
     database = f['database']
     database = f['database']
     driver = f['driver']
     driver = f['driver']
-    
+
     if not table:
     if not table:
         grass.fatal(_("There is no table connected to the input vector map. "
         grass.fatal(_("There is no table connected to the input vector map. "
                       "Unable to delete any column. Exiting."))
                       "Unable to delete any column. Exiting."))
-    
+
     if keycol in columns:
     if keycol in columns:
         grass.fatal(_("Unable to delete <%s> column as it is needed to keep table <%s> "
         grass.fatal(_("Unable to delete <%s> column as it is needed to keep table <%s> "
-                      "connected to the input vector map <%s>") % \
-                        (keycol, table, map))
-    
+                      "connected to the input vector map <%s>") %
+                    (keycol, table, map))
+
     for column in columns:
     for column in columns:
-        if not grass.vector_columns(map, layer).has_key(column):
+        if column not in grass.vector_columns(map, layer):
             grass.warning(_("Column <%s> not found in table <%s>. Skipped") % (column, table))
             grass.warning(_("Column <%s> not found in table <%s>. Skipped") % (column, table))
             continue
             continue
-        
+
         if driver == "sqlite":
         if driver == "sqlite":
             # echo "Using special trick for SQLite"
             # echo "Using special trick for SQLite"
             # http://www.sqlite.org/faq.html#q11
             # http://www.sqlite.org/faq.html#q11
             colnames = []
             colnames = []
             coltypes = []
             coltypes = []
-            for f in grass.db_describe(table, database = database, driver = driver)['cols']:
+            for f in grass.db_describe(table, database=database, driver=driver)['cols']:
                 if f[0] == column:
                 if f[0] == column:
                     continue
                     continue
                 colnames.append(f[0])
                 colnames.append(f[0])
@@ -100,21 +100,21 @@ def main():
                 "CREATE UNIQUE INDEX ${table}_cat ON ${table} (${keycol} )",
                 "CREATE UNIQUE INDEX ${table}_cat ON ${table} (${keycol} )",
                 "DROP TABLE ${table}_backup",
                 "DROP TABLE ${table}_backup",
                 "COMMIT"
                 "COMMIT"
-                ]
+            ]
             tmpl = string.Template(';\n'.join(cmds))
             tmpl = string.Template(';\n'.join(cmds))
-            sql = tmpl.substitute(table = table, coldef = coltypes, colnames = colnames, keycol = keycol)
+            sql = tmpl.substitute(table=table, coldef=coltypes, colnames=colnames, keycol=keycol)
         else:
         else:
             sql = "ALTER TABLE %s DROP COLUMN %s" % (table, column)
             sql = "ALTER TABLE %s DROP COLUMN %s" % (table, column)
 
 
         try:
         try:
-            grass.write_command('db.execute', input = '-', database = database, driver = driver,
-                                stdin = sql)
+            grass.write_command('db.execute', input='-', database=database, driver=driver,
+                                stdin=sql)
         except CalledModuleError:
         except CalledModuleError:
             grass.fatal(_("Deleting column failed"))
             grass.fatal(_("Deleting column failed"))
-    
+
     # write cmd history:
     # write cmd history:
     grass.vector_history(map)
     grass.vector_history(map)
-    
+
 if __name__ == "__main__":
 if __name__ == "__main__":
     options, flags = grass.parser()
     options, flags = grass.parser()
     main()
     main()

+ 1 - 1
scripts/v.db.droprow/v.db.droprow.py

@@ -51,7 +51,7 @@ def main():
         return 1
         return 1
 
 
     # write cmd history:
     # write cmd history:
-    grass.vector_history(map = options['output'])
+    grass.vector_history(map=options['output'])
 
 
     return 0
     return 0
 
 

+ 34 - 32
scripts/v.db.droptable/v.db.droptable.py

@@ -3,7 +3,7 @@
 ############################################################################
 ############################################################################
 #
 #
 # MODULE:       v.db.droptable
 # MODULE:       v.db.droptable
-# AUTHOR(S):   	Markus Neteler 
+# AUTHOR(S):   	Markus Neteler
 #               Converted to Python by Glynn Clements
 #               Converted to Python by Glynn Clements
 # PURPOSE:      interface to db.execute to drop an existing table of given vector map
 # PURPOSE:      interface to db.execute to drop an existing table of given vector map
 # COPYRIGHT:    (C) 2005, 2008 by the GRASS Development Team
 # COPYRIGHT:    (C) 2005, 2008 by the GRASS Development Team
@@ -36,7 +36,7 @@
 
 
 import sys
 import sys
 import os
 import os
-import grass.script as grass
+import grass.script as gscript
 from grass.exceptions import CalledModuleError
 from grass.exceptions import CalledModuleError
 
 
 
 
@@ -47,56 +47,58 @@ def main():
     layer = options['layer']
     layer = options['layer']
 
 
     # do some paranoia tests as well:
     # do some paranoia tests as well:
-    f = grass.vector_layer_db(map, layer)
-    
+    f = gscript.vector_layer_db(map, layer)
+
     if not table:
     if not table:
-	# Removing table name connected to selected layer
-	table = f['table']
-	if not table:
-	    grass.fatal(_("No table assigned to layer <%s>") % layer)
+        # Removing table name connected to selected layer
+        table = f['table']
+        if not table:
+            gscript.fatal(_("No table assigned to layer <%s>") % layer)
     else:
     else:
-	# Removing user specified table
-	existingtable = f['table']
-	if existingtable != table:
-	    grass.fatal(_("User selected table <%s> but the table <%s> is linked to layer <%s>")
-			% (table, existingtable, layer))
-
-    # we use the DB settings selected layer 
+        # Removing user specified table
+        existingtable = f['table']
+        if existingtable != table:
+            gscript.fatal(_("User selected table <%s> but the table <%s> "
+                            "is linked to layer <%s>") %
+                          (table, existingtable, layer))
+
+    # we use the DB settings selected layer
     database = f['database']
     database = f['database']
     driver = f['driver']
     driver = f['driver']
 
 
-    grass.message(_("Removing table <%s> linked to layer <%s> of vector map <%s>")
-		  % (table, layer, map)) 
+    gscript.message(_("Removing table <%s> linked to layer <%s> of vector"
+                      " map <%s>") % (table, layer, map))
 
 
     if not force:
     if not force:
-	grass.message(_("You must use the -f (force) flag to actually remove the table. Exiting."))
-	grass.message(_("Leaving map/table unchanged."))
-	sys.exit(0)
+        gscript.message(_("You must use the -f (force) flag to actually "
+                          "remove the table. Exiting."))
+        gscript.message(_("Leaving map/table unchanged."))
+        sys.exit(0)
 
 
-    grass.message(_("Dropping table <%s>...") % table)
+    gscript.message(_("Dropping table <%s>...") % table)
 
 
     try:
     try:
-        grass.write_command('db.execute', stdin="DROP TABLE %s" % table,
-                            input='-', database=database, driver=driver)
+        gscript.write_command('db.execute', stdin="DROP TABLE %s" % table,
+                              input='-', database=database, driver=driver)
     except CalledModuleError:
     except CalledModuleError:
-        grass.fatal(_("An error occurred while running db.execute"))
+        gscript.fatal(_("An error occurred while running db.execute"))
 
 
-    grass.run_command('v.db.connect', flags = 'd', map = map, layer = layer)
+    gscript.run_command('v.db.connect', flags='d', map=map, layer=layer)
 
 
-    grass.message(_("Current attribute table link(s):")) 
+    gscript.message(_("Current attribute table link(s):"))
     # silently test first to avoid confusing error messages
     # silently test first to avoid confusing error messages
     nuldev = file(os.devnull, 'w')
     nuldev = file(os.devnull, 'w')
     try:
     try:
-        grass.run_command('v.db.connect', flags='p', map=map, quiet=True,
-                          stdout=nuldev, stderr=nuldev)
+        gscript.run_command('v.db.connect', flags='p', map=map, quiet=True,
+                            stdout=nuldev, stderr=nuldev)
     except CalledModuleError:
     except CalledModuleError:
-        grass.message(_("(No database links remaining)"))
+        gscript.message(_("(No database links remaining)"))
     else:
     else:
-        grass.run_command('v.db.connect', flags='p', map=map)
+        gscript.run_command('v.db.connect', flags='p', map=map)
 
 
     # write cmd history:
     # write cmd history:
-    grass.vector_history(map)
+    gscript.vector_history(map)
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     main()
     main()

+ 5 - 3
scripts/v.db.join/v.db.join.py

@@ -77,7 +77,7 @@ def main():
 
 
     maptable = f['table']
     maptable = f['table']
     database = f['database']
     database = f['database']
-    driver   = f['driver']
+    driver = f['driver']
 
 
     if driver == 'dbf':
     if driver == 'dbf':
         grass.fatal(_("JOIN is not supported for tables stored in DBF format"))
         grass.fatal(_("JOIN is not supported for tables stored in DBF format"))
@@ -86,7 +86,7 @@ def main():
         grass.fatal(_("There is no table connected to this map. Unable to join any column."))
         grass.fatal(_("There is no table connected to this map. Unable to join any column."))
 
 
     # check if column is in map table
     # check if column is in map table
-    if not grass.vector_columns(map, layer).has_key(column):
+    if column not in grass.vector_columns(map, layer):
         grass.fatal(_("Column <%s> not found in table <%s>") % (column,
         grass.fatal(_("Column <%s> not found in table <%s>") % (column,
                                                                 maptable))
                                                                 maptable))
 
 
@@ -154,7 +154,9 @@ def main():
                                    otable=otable, ocolumn=ocolumn,
                                    otable=otable, ocolumn=ocolumn,
                                    colname=colname)
                                    colname=colname)
         grass.debug(stmt, 1)
         grass.debug(stmt, 1)
-        grass.verbose(_("Updating column <%s> of vector map <%s>...") % (colname, map))
+        grass.verbose(
+            _("Updating column <%s> of vector map <%s>...") %
+            (colname, map))
         try:
         try:
             grass.write_command('db.execute', stdin=stmt, input='-',
             grass.write_command('db.execute', stdin=stmt, input='-',
                                 database=database, driver=driver)
                                 database=database, driver=driver)

+ 115 - 90
scripts/v.db.reconnect.all/v.db.reconnect.all.py

@@ -53,107 +53,120 @@ import sys
 import os
 import os
 import string
 import string
 
 
-import grass.script as grass
+import grass.script as gscript
 from grass.exceptions import CalledModuleError
 from grass.exceptions import CalledModuleError
 
 
 # substitute variables (gisdbase, location_name, mapset)
 # substitute variables (gisdbase, location_name, mapset)
+
+
 def substitute_db(database):
 def substitute_db(database):
-    gisenv = grass.gisenv()
+    gisenv = gscript.gisenv()
     tmpl = string.Template(database)
     tmpl = string.Template(database)
-    
-    return tmpl.substitute(GISDBASE = gisenv['GISDBASE'],
-                           LOCATION_NAME = gisenv['LOCATION_NAME'],
-                           MAPSET = gisenv['MAPSET'])
+
+    return tmpl.substitute(GISDBASE=gisenv['GISDBASE'],
+                           LOCATION_NAME=gisenv['LOCATION_NAME'],
+                           MAPSET=gisenv['MAPSET'])
 
 
 # create database if doesn't exist
 # create database if doesn't exist
+
+
 def create_db(driver, database):
 def create_db(driver, database):
     subst_database = substitute_db(database)
     subst_database = substitute_db(database)
     if driver == 'dbf':
     if driver == 'dbf':
         path = subst_database
         path = subst_database
         # check if destination directory exists
         # check if destination directory exists
         if not os.path.isdir(path):
         if not os.path.isdir(path):
-	    # create dbf database
+            # create dbf database
             os.makedirs(path)
             os.makedirs(path)
-	    return True
+            return True
         return False
         return False
-    
+
     if driver == 'sqlite':
     if driver == 'sqlite':
         path = os.path.dirname(subst_database)
         path = os.path.dirname(subst_database)
         # check if destination directory exists
         # check if destination directory exists
         if not os.path.isdir(path):
         if not os.path.isdir(path):
             os.makedirs(path)
             os.makedirs(path)
-    
-    if subst_database in grass.read_command('db.databases', quiet = True,
-                                      driver = driver).splitlines():
+
+    if subst_database in gscript.read_command('db.databases', quiet=True,
+                                              driver=driver).splitlines():
         return False
         return False
 
 
-    grass.info(_("Target database doesn't exist, "
-                 "creating a new database using <%s> driver...") % driver)
+    gscript.info(_("Target database doesn't exist, "
+                   "creating a new database using <%s> driver...") % driver)
     try:
     try:
-        grass.run_command('db.createdb', driver = driver,
-                          database = subst_database)
+        gscript.run_command('db.createdb', driver=driver,
+                            database=subst_database)
     except CalledModuleError:
     except CalledModuleError:
-        grass.fatal(_("Unable to create database <%s> by driver <%s>") % \
-                        (subst_database, driver))
-        
+        gscript.fatal(_("Unable to create database <%s> by driver <%s>") %
+                      (subst_database, driver))
+
     return False
     return False
 
 
 # copy tables if required (-c)
 # copy tables if required (-c)
+
+
 def copy_tab(from_driver, from_database, from_table,
 def copy_tab(from_driver, from_database, from_table,
              to_driver, to_database, to_table):
              to_driver, to_database, to_table):
-    if to_table in grass.read_command('db.tables', quiet = True,
-                                      driver = to_driver,
-                                      database = to_database,
-                                      stderr = nuldev).splitlines():
+    if to_table in gscript.read_command('db.tables', quiet=True,
+                                        driver=to_driver,
+                                        database=to_database,
+                                        stderr=nuldev).splitlines():
         return False
         return False
-    
-    grass.info("Copying table <%s> to target database..." % to_table)
+
+    gscript.info("Copying table <%s> to target database..." % to_table)
     try:
     try:
-        grass.run_command('db.copy', from_driver = from_driver,
-                          from_database = from_database,
-                          from_table = from_table, to_driver = to_driver,
-                          to_database = to_database,
-                          to_table = to_table)
+        gscript.run_command('db.copy', from_driver=from_driver,
+                            from_database=from_database,
+                            from_table=from_table, to_driver=to_driver,
+                            to_database=to_database,
+                            to_table=to_table)
     except CalledModuleError:
     except CalledModuleError:
-        grass.fatal(_("Unable to copy table <%s>") % from_table)
-    
+        gscript.fatal(_("Unable to copy table <%s>") % from_table)
+
     return True
     return True
 
 
 # drop tables if required (-d)
 # drop tables if required (-d)
+
+
 def drop_tab(vector, layer, table, driver, database):
 def drop_tab(vector, layer, table, driver, database):
     # disconnect
     # disconnect
     try:
     try:
-        grass.run_command('v.db.connect', flags = 'd', quiet = True, map = vector,
-			          layer = layer, table = table)
+        gscript.run_command('v.db.connect', flags='d', quiet=True, map=vector,
+                            layer=layer, table=table)
     except CalledModuleError:
     except CalledModuleError:
-        grass.warning(_("Unable to disconnect table <%s> from vector <%s>") % (table, vector))
+        gscript.warning(_("Unable to disconnect table <%s> from vector <%s>") %
+                        (table, vector))
     # drop table
     # drop table
     try:
     try:
-        grass.run_command('db.droptable', quiet = True, flags = 'f',
-                          driver = driver, database = database,
-                          table = table)
+        gscript.run_command('db.droptable', quiet=True, flags='f',
+                            driver=driver, database=database,
+                            table=table)
     except CalledModuleError:
     except CalledModuleError:
-        grass.fatal(_("Unable to drop table <%s>") % table)
-        
+        gscript.fatal(_("Unable to drop table <%s>") % table)
+
 # create index on key column
 # create index on key column
+
+
 def create_index(driver, database, table, index_name, key):
 def create_index(driver, database, table, index_name, key):
     if driver == 'dbf':
     if driver == 'dbf':
-	return False
+        return False
 
 
-    grass.info(_("Creating index <%s>...") % index_name)
+    gscript.info(_("Creating index <%s>...") % index_name)
     try:
     try:
-        grass.run_command('db.execute', quiet = True,
-                          driver = driver, database = database,
-                          sql = "create unique index %s on %s(%s)" % (index_name, table, key))
+        gscript.run_command('db.execute', quiet=True, driver=driver,
+                            database=database,
+                            sql="create unique index %s on %s(%s)" %
+                                (index_name, table, key))
     except CalledModuleError:
     except CalledModuleError:
-        grass.warning(_("Unable to create index <%s>") % index_name)
+        gscript.warning(_("Unable to create index <%s>") % index_name)
+
 
 
 def main():
 def main():
     # old connection
     # old connection
     old_database = options['old_database']
     old_database = options['old_database']
     old_schema = options['old_schema']
     old_schema = options['old_schema']
     # new connection
     # new connection
-    default_connection = grass.db_connection()
+    default_connection = gscript.db_connection()
     if options['new_driver']:
     if options['new_driver']:
         new_driver = options['new_driver']
         new_driver = options['new_driver']
     else:
     else:
@@ -168,93 +181,105 @@ def main():
         new_schema = default_connection['schema']
         new_schema = default_connection['schema']
 
 
     if old_database == '':
     if old_database == '':
-    	old_database = None
+        old_database = None
     old_database_subst = None
     old_database_subst = None
     if old_database is not None:
     if old_database is not None:
-	old_database_subst = substitute_db(old_database)
+        old_database_subst = substitute_db(old_database)
 
 
     new_database_subst = substitute_db(new_database)
     new_database_subst = substitute_db(new_database)
-    
+
     if old_database_subst == new_database_subst and old_schema == new_schema:
     if old_database_subst == new_database_subst and old_schema == new_schema:
-	grass.fatal(_("Old and new database connection is identical. Nothing to do."))
-    
-    mapset = grass.gisenv()['MAPSET']
-        
-    vectors = grass.list_grouped('vect')[mapset]
+        gscript.fatal(_("Old and new database connection is identical. "
+                        "Nothing to do."))
+
+    mapset = gscript.gisenv()['MAPSET']
+
+    vectors = gscript.list_grouped('vect')[mapset]
     num_vectors = len(vectors)
     num_vectors = len(vectors)
 
 
     if flags['c']:
     if flags['c']:
-	# create new database if not existing
-	create_db(new_driver, new_database)
-    
+        # create new database if not existing
+        create_db(new_driver, new_database)
+
     i = 0
     i = 0
     for vect in vectors:
     for vect in vectors:
         vect = "%s@%s" % (vect, mapset)
         vect = "%s@%s" % (vect, mapset)
         i += 1
         i += 1
-	grass.message(_("%s\nReconnecting vector map <%s> (%d of %d)...\n%s") % \
-                          ('-' * 80, vect, i, num_vectors, '-' * 80))
-        for f in grass.vector_db(vect, stderr = nuldev).itervalues():
+        gscript.message(_("%s\nReconnecting vector map <%s> "
+                          "(%d of %d)...\n%s") %
+                        ('-' * 80, vect, i, num_vectors, '-' * 80))
+        for f in gscript.vector_db(vect, stderr=nuldev).itervalues():
             layer = f['layer']
             layer = f['layer']
             schema_table = f['table']
             schema_table = f['table']
             key = f['key']
             key = f['key']
             database = f['database']
             database = f['database']
             driver = f['driver']
             driver = f['driver']
-            
+
             # split schema.table
             # split schema.table
             if '.' in schema_table:
             if '.' in schema_table:
                 schema, table = schema_table.split('.', 1)
                 schema, table = schema_table.split('.', 1)
             else:
             else:
                 schema = ''
                 schema = ''
                 table = schema_table
                 table = schema_table
-            
+
             if new_schema:
             if new_schema:
                 new_schema_table = "%s.%s" % (new_schema, table)
                 new_schema_table = "%s.%s" % (new_schema, table)
             else:
             else:
                 new_schema_table = table
                 new_schema_table = table
-            
-            grass.debug("DATABASE = '%s' SCHEMA = '%s' TABLE = '%s' ->\n"
-                        "      NEW_DATABASE = '%s' NEW_SCHEMA_TABLE = '%s'" % \
-                            (old_database, schema, table, new_database, new_schema_table))
+
+            gscript.debug("DATABASE = '%s' SCHEMA = '%s' TABLE = '%s' ->\n"
+                          "      NEW_DATABASE = '%s' NEW_SCHEMA_TABLE = '%s'" %
+                          (old_database, schema, table, new_database,
+                           new_schema_table))
 
 
             do_reconnect = True
             do_reconnect = True
-	    if old_database_subst is not None:
-		if database != old_database_subst:
-		    do_reconnect = False
-	    if database == new_database_subst:
-		do_reconnect = False
-	    if schema != old_schema:
-		do_reconnect = False
-		
+            if old_database_subst is not None:
+                if database != old_database_subst:
+                    do_reconnect = False
+            if database == new_database_subst:
+                do_reconnect = False
+            if schema != old_schema:
+                do_reconnect = False
+
             if do_reconnect == True:
             if do_reconnect == True:
-                grass.verbose(_("Reconnecting layer %d...") % layer)
-                                          
+                gscript.verbose(_("Reconnecting layer %d...") % layer)
+
                 if flags['c']:
                 if flags['c']:
                     # check if table exists in new database
                     # check if table exists in new database
                     copy_tab(driver, database, schema_table,
                     copy_tab(driver, database, schema_table,
                              new_driver, new_database, new_schema_table)
                              new_driver, new_database, new_schema_table)
-                
+
                 # drop original table if required
                 # drop original table if required
                 if flags['d']:
                 if flags['d']:
-                    drop_tab(vect, layer, schema_table, driver, substitute_db(database))
+                    drop_tab(
+                        vect,
+                        layer,
+                        schema_table,
+                        driver,
+                        substitute_db(database))
 
 
                 # reconnect tables (don't use substituted new_database)
                 # reconnect tables (don't use substituted new_database)
-		# NOTE: v.db.connect creates an index on the key column
+                # NOTE: v.db.connect creates an index on the key column
                 try:
                 try:
-                    grass.run_command('v.db.connect', flags = 'o', quiet = True, map = vect,
-                                      layer = layer, driver = new_driver, database = new_database,
-                                      table = new_schema_table, key = key)
+                    gscript.run_command('v.db.connect', flags='o', quiet=True,
+                                        map=vect, layer=layer,
+                                        driver=new_driver,
+                                        database=new_database,
+                                        table=new_schema_table, key=key)
                 except CalledModuleError:
                 except CalledModuleError:
-                    grass.warning(_("Unable to connect table <%s> to vector <%s> on layer <%s>") %
-				  (table, vect, str(layer)))
+                    gscript.warning(_("Unable to connect table <%s> to vector "
+                                      "<%s> on layer <%s>") %
+                                    (table, vect, str(layer)))
 
 
             else:
             else:
-		if database != new_database_subst:
-		    grass.warning(_("Layer <%d> will not be reconnected because "
-				    "database or schema do not match.") % layer)
-	
+                if database != new_database_subst:
+                    gscript.warning(_("Layer <%d> will not be reconnected "
+                                      "because database or schema do not "
+                                      "match.") % layer)
+
     return 0
     return 0
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     nuldev = file(os.devnull, 'w')
     nuldev = file(os.devnull, 'w')
     sys.exit(main())
     sys.exit(main())

+ 16 - 11
scripts/v.db.renamecolumn/v.db.renamecolumn.py

@@ -5,10 +5,10 @@
 # MODULE:       v.db.renamecolumn
 # MODULE:       v.db.renamecolumn
 # AUTHOR(S):    Markus Neteler
 # AUTHOR(S):    Markus Neteler
 #               Converted to Python by Glynn Clements
 #               Converted to Python by Glynn Clements
-# PURPOSE:      interface to db.execute to drop a column from the 
+# PURPOSE:      interface to db.execute to drop a column from the
 #               attribute table connected to a given vector map
 #               attribute table connected to a given vector map
 #               - Based on v.db.dropcolumn
 #               - Based on v.db.dropcolumn
-#               - with special trick for SQLite and DBF (here the new col is 
+#               - with special trick for SQLite and DBF (here the new col is
 #                 added/values copied/old col deleted)
 #                 added/values copied/old col deleted)
 # COPYRIGHT:    (C) 2007 by the GRASS Development Team
 # COPYRIGHT:    (C) 2007 by the GRASS Development Team
 #
 #
@@ -30,7 +30,7 @@
 #%end
 #%end
 #%option G_OPT_V_FIELD
 #%option G_OPT_V_FIELD
 #%end
 #%end
-#%option 
+#%option
 #% key: column
 #% key: column
 #% type: string
 #% type: string
 #% description: Old and new name of the column (old,new)
 #% description: Old and new name of the column (old,new)
@@ -43,6 +43,7 @@ import sys
 import os
 import os
 import grass.script as grass
 import grass.script as grass
 
 
+
 def main():
 def main():
     map = options['map']
     map = options['map']
     layer = options['layer']
     layer = options['layer']
@@ -50,7 +51,7 @@ def main():
 
 
     mapset = grass.gisenv()['MAPSET']
     mapset = grass.gisenv()['MAPSET']
 
 
-    if not grass.find_file(map, element = 'vector', mapset = mapset):
+    if not grass.find_file(map, element='vector', mapset=mapset):
         grass.fatal(_("Vector map <%s> not found in current mapset") % map)
         grass.fatal(_("Vector map <%s> not found in current mapset") % map)
 
 
     f = grass.vector_layer_db(map, layer)
     f = grass.vector_layer_db(map, layer)
@@ -69,10 +70,14 @@ def main():
 
 
     if driver == "dbf":
     if driver == "dbf":
         if len(newcol) > 10:
         if len(newcol) > 10:
-            grass.fatal(_("Column name <%s> too long. The DBF driver supports column names not longer than 10 characters") % newcol)
+            grass.fatal(
+                _("Column name <%s> too long. The DBF driver supports column names not longer than 10 characters") %
+                newcol)
 
 
     if oldcol == keycol:
     if oldcol == keycol:
-        grass.fatal(_("Cannot rename column <%s> as it is needed to keep table <%s> connected to the input vector map") % (oldcol, table))
+        grass.fatal(
+            _("Cannot rename column <%s> as it is needed to keep table <%s> connected to the input vector map") %
+            (oldcol, table))
 
 
     # describe old col
     # describe old col
     oldcoltype = None
     oldcoltype = None
@@ -93,10 +98,10 @@ def main():
         else:
         else:
             colspec = "%s %s" % (newcol, oldcoltype)
             colspec = "%s %s" % (newcol, oldcoltype)
 
 
-        grass.run_command('v.db.addcolumn', map = map, layer = layer, column = colspec)
+        grass.run_command('v.db.addcolumn', map=map, layer=layer, column=colspec)
         sql = "UPDATE %s SET %s=%s" % (table, newcol, oldcol)
         sql = "UPDATE %s SET %s=%s" % (table, newcol, oldcol)
-        grass.write_command('db.execute', input = '-', database = database, driver = driver, stdin = sql)
-        grass.run_command('v.db.dropcolumn', map = map, layer = layer, column = oldcol)
+        grass.write_command('db.execute', input='-', database=database, driver=driver, stdin=sql)
+        grass.run_command('v.db.dropcolumn', map=map, layer=layer, column=oldcol)
     elif driver == 'mysql':
     elif driver == 'mysql':
         if oldcoltype.upper() == "CHARACTER":
         if oldcoltype.upper() == "CHARACTER":
             newcoltype = "varchar(%s)" % (oldcollength)
             newcoltype = "varchar(%s)" % (oldcollength)
@@ -104,10 +109,10 @@ def main():
             newcoltype = oldcoltype
             newcoltype = oldcoltype
 
 
         sql = "ALTER TABLE %s CHANGE %s %s %s" % (table, oldcol, newcol, newcoltype)
         sql = "ALTER TABLE %s CHANGE %s %s %s" % (table, oldcol, newcol, newcoltype)
-        grass.write_command('db.execute', input = '-', database = database, driver = driver, stdin = sql)
+        grass.write_command('db.execute', input='-', database=database, driver=driver, stdin=sql)
     else:
     else:
         sql = "ALTER TABLE %s RENAME %s TO %s" % (table, oldcol, newcol)
         sql = "ALTER TABLE %s RENAME %s TO %s" % (table, oldcol, newcol)
-        grass.write_command('db.execute', input = '-', database = database, driver = driver, stdin = sql)
+        grass.write_command('db.execute', input='-', database=database, driver=driver, stdin=sql)
 
 
     # write cmd history:
     # write cmd history:
     grass.vector_history(map)
     grass.vector_history(map)

+ 19 - 20
scripts/v.db.univar/v.db.univar.py

@@ -53,50 +53,49 @@
 
 
 import sys
 import sys
 import os
 import os
-import grass.script as grass
+import grass.script as gscript
 from grass.exceptions import CalledModuleError
 from grass.exceptions import CalledModuleError
 
 
+
 def main():
 def main():
     global tmp
     global tmp
-    tmp = grass.tempfile()
+    tmp = gscript.tempfile()
 
 
     vector = options['map']
     vector = options['map']
     layer = options['layer']
     layer = options['layer']
     column = options['column']
     column = options['column']
     where = options['where']
     where = options['where']
     perc = options['percentile']
     perc = options['percentile']
-    extend = flags['e']
-    shellstyle = flags['g']
 
 
-    if not grass.find_file(vector, element='vector')['file']:
-        grass.fatal(_("Vector map <%s> not found") % vector)
+    if not gscript.find_file(vector, element='vector')['file']:
+        gscript.fatal(_("Vector map <%s> not found") % vector)
 
 
     try:
     try:
-        fi = grass.vector_db(vector, stderr = nuldev)[int(layer)]
+        fi = gscript.vector_db(vector, stderr=nuldev)[int(layer)]
     except KeyError:
     except KeyError:
-        grass.fatal(_("No attribute table linked to layer <%s>") % layer)
-                
+        gscript.fatal(_("No attribute table linked to layer <%s>") % layer)
+
     table = fi['table']
     table = fi['table']
     database = fi['database']
     database = fi['database']
     driver = fi['driver']
     driver = fi['driver']
-    
+
     passflags = None
     passflags = None
     if flags['e']:
     if flags['e']:
-	passflags = 'e'
+        passflags = 'e'
     if flags['g']:
     if flags['g']:
-	if not passflags:
-	    passflags = 'g'
-	else:
-	    passflags = passflags + 'g'
+        if not passflags:
+            passflags = 'g'
+        else:
+            passflags = passflags + 'g'
 
 
     try:
     try:
-        grass.run_command('db.univar', table = table, column = column, 
-                          database = database, driver = driver,
-                          perc = perc, where = where, flags = passflags)
+        gscript.run_command('db.univar', table=table, column=column,
+                            database=database, driver=driver,
+                            perc=perc, where=where, flags=passflags)
     except CalledModuleError:
     except CalledModuleError:
         sys.exit(1)
         sys.exit(1)
-    
+
 if __name__ == "__main__":
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     nuldev = file(os.devnull, 'w')
     nuldev = file(os.devnull, 'w')
     main()
     main()

+ 6 - 4
scripts/v.db.update/v.db.update.py

@@ -54,6 +54,7 @@ import sys
 import os
 import os
 import grass.script as grass
 import grass.script as grass
 
 
+
 def main():
 def main():
     vector = options['map']
     vector = options['map']
     layer = options['layer']
     layer = options['layer']
@@ -61,18 +62,19 @@ def main():
     value = options['value']
     value = options['value']
     qcolumn = options['query_column']
     qcolumn = options['query_column']
     where = options['where']
     where = options['where']
-    sqlitefile  = options['sqliteextra']
+    sqlitefile = options['sqliteextra']
 
 
     mapset = grass.gisenv()['MAPSET']
     mapset = grass.gisenv()['MAPSET']
 
 
     # does map exist in CURRENT mapset?
     # does map exist in CURRENT mapset?
-    if not grass.find_file(vector, element = 'vector', mapset = mapset)['file']:
+    if not grass.find_file(vector, element='vector', mapset=mapset)['file']:
         grass.fatal(_("Vector map <%s> not found in current mapset") % vector)
         grass.fatal(_("Vector map <%s> not found in current mapset") % vector)
 
 
     try:
     try:
         f = grass.vector_db(vector)[int(layer)]
         f = grass.vector_db(vector)[int(layer)]
     except KeyError:
     except KeyError:
-        grass.fatal(_('There is no table connected to this map. Run v.db.connect or v.db.addtable first.'))
+        grass.fatal(
+            _('There is no table connected to this map. Run v.db.connect or v.db.addtable first.'))
 
 
     table = f['table']
     table = f['table']
     database = f['database']
     database = f['database']
@@ -113,7 +115,7 @@ def main():
         cmd = sqliteload + cmd
         cmd = sqliteload + cmd
 
 
     grass.verbose("SQL: \"%s\"" % cmd)
     grass.verbose("SQL: \"%s\"" % cmd)
-    grass.write_command('db.execute', input = '-', database = database, driver = driver, stdin = cmd)
+    grass.write_command('db.execute', input='-', database=database, driver=driver, stdin=cmd)
 
 
     # write cmd history:
     # write cmd history:
     grass.vector_history(vector)
     grass.vector_history(vector)

+ 20 - 16
scripts/v.dissolve/v.dissolve.py

@@ -43,7 +43,10 @@ from grass.exceptions import CalledModuleError
 
 
 def cleanup():
 def cleanup():
     nuldev = file(os.devnull, 'w')
     nuldev = file(os.devnull, 'w')
-    grass.run_command('g.remove', flags = 'f', type = 'vector', name = '%s_%s' % (output, tmp), quiet = True, stderr = nuldev)
+    grass.run_command(
+        'g.remove', flags='f', type='vector', name='%s_%s' %
+        (output, tmp), quiet=True, stderr=nuldev)
+
 
 
 def main():
 def main():
     global output, tmp
     global output, tmp
@@ -53,44 +56,45 @@ def main():
     layer = options['layer']
     layer = options['layer']
     column = options['column']
     column = options['column']
 
 
-    #### setup temporary file
+    # setup temporary file
     tmp = str(os.getpid())
     tmp = str(os.getpid())
 
 
     # does map exist?
     # does map exist?
-    if not grass.find_file(input, element = 'vector')['file']:
-	grass.fatal(_("Vector map <%s> not found") % input)
-    
+    if not grass.find_file(input, element='vector')['file']:
+        grass.fatal(_("Vector map <%s> not found") % input)
+
     if not column:
     if not column:
-        grass.warning(_("No '%s' option specified. Dissolving based on category values from layer <%s>.") % \
-                          ("column", layer))
-	grass.run_command('v.extract', flags = 'd', input = input,
-			  output = output, type = 'area', layer = layer)
+        grass.warning(
+            _("No '%s' option specified. Dissolving based on category values from layer <%s>.") %
+            ("column", layer))
+        grass.run_command('v.extract', flags='d', input=input,
+                          output=output, type='area', layer=layer)
     else:
     else:
         if int(layer) == -1:
         if int(layer) == -1:
             grass.warning(_("Invalid layer number (%d). "
             grass.warning(_("Invalid layer number (%d). "
-                            "Parameter '%s' specified, assuming layer '1'.") % 
+                            "Parameter '%s' specified, assuming layer '1'.") %
                           (int(layer), 'column'))
                           (int(layer), 'column'))
             layer = '1'
             layer = '1'
         try:
         try:
             coltype = grass.vector_columns(input, layer)[column]
             coltype = grass.vector_columns(input, layer)[column]
         except KeyError:
         except KeyError:
             grass.fatal(_('Column <%s> not found') % column)
             grass.fatal(_('Column <%s> not found') % column)
-        
-	if coltype['type'] not in ('INTEGER', 'SMALLINT', 'CHARACTER', 'TEXT'):
-	    grass.fatal(_("Key column must be of type integer or string"))
+
+        if coltype['type'] not in ('INTEGER', 'SMALLINT', 'CHARACTER', 'TEXT'):
+            grass.fatal(_("Key column must be of type integer or string"))
 
 
         f = grass.vector_layer_db(input, layer)
         f = grass.vector_layer_db(input, layer)
 
 
-	table = f['table']
+        table = f['table']
 
 
-	tmpfile = '%s_%s' % (output, tmp)
+        tmpfile = '%s_%s' % (output, tmp)
 
 
         try:
         try:
             grass.run_command('v.reclass', input=input, output=tmpfile,
             grass.run_command('v.reclass', input=input, output=tmpfile,
                               layer=layer, column=column)
                               layer=layer, column=column)
             grass.run_command('v.extract', flags='d', input=tmpfile,
             grass.run_command('v.extract', flags='d', input=tmpfile,
                               output=output, type='area', layer=layer)
                               output=output, type='area', layer=layer)
-        except CalledModuleError, e:
+        except CalledModuleError as e:
             grass.fatal(_("Final extraction steps failed."
             grass.fatal(_("Final extraction steps failed."
                           " Check above error messages and"
                           " Check above error messages and"
                           " see following details:\n%s") % e)
                           " see following details:\n%s") % e)

+ 11 - 7
scripts/v.import/v.import.py

@@ -153,10 +153,10 @@ def main():
         # list datum transform parameters
         # list datum transform parameters
         if not options['epsg']:
         if not options['epsg']:
             grass.fatal(_("Missing value for parameter <%s>") % 'epsg')
             grass.fatal(_("Missing value for parameter <%s>") % 'epsg')
-        
+
         return grass.run_command('g.proj', epsg=options['epsg'],
         return grass.run_command('g.proj', epsg=options['epsg'],
                                  datum_trans=options['datum_trans'])
                                  datum_trans=options['datum_trans'])
-    
+
     grassenv = grass.gisenv()
     grassenv = grass.gisenv()
     tgtloc = grassenv['LOCATION_NAME']
     tgtloc = grassenv['LOCATION_NAME']
     tgtmapset = grassenv['MAPSET']
     tgtmapset = grassenv['MAPSET']
@@ -191,12 +191,12 @@ def main():
     # switch to temp location
     # switch to temp location
     os.environ['GISRC'] = str(SRCGISRC)
     os.environ['GISRC'] = str(SRCGISRC)
 
 
-    if options['epsg']: # force given EPSG
+    if options['epsg']:  # force given EPSG
         kwargs = {}
         kwargs = {}
         if options['datum_trans']:
         if options['datum_trans']:
             kwargs['datum_trans'] = options['datum_trans']
             kwargs['datum_trans'] = options['datum_trans']
         grass.run_command('g.proj', flags='c', epsg=options['epsg'], **kwargs)
         grass.run_command('g.proj', flags='c', epsg=options['epsg'], **kwargs)
-        
+
     # switch to target location
     # switch to target location
     os.environ['GISRC'] = str(tgtgisrc)
     os.environ['GISRC'] = str(tgtgisrc)
 
 
@@ -206,21 +206,25 @@ def main():
         try:
         try:
             grass.run_command('v.in.ogr', input=OGRdatasource,
             grass.run_command('v.in.ogr', input=OGRdatasource,
                               flags=vflags, overwrite=overwrite, **vopts)
                               flags=vflags, overwrite=overwrite, **vopts)
-            grass.message(_("Input <%s> successfully imported without reprojection") % OGRdatasource)
+            grass.message(
+                _("Input <%s> successfully imported without reprojection") %
+                OGRdatasource)
             return 0
             return 0
         except CalledModuleError:
         except CalledModuleError:
             grass.fatal(_("Unable to import <%s>") % OGRdatasource)
             grass.fatal(_("Unable to import <%s>") % OGRdatasource)
 
 
     # make sure target is not xy
     # make sure target is not xy
     if grass.parse_command('g.proj', flags='g')['name'] == 'xy_location_unprojected':
     if grass.parse_command('g.proj', flags='g')['name'] == 'xy_location_unprojected':
-        grass.fatal(_("Coordinate reference system not available for current location <%s>") % tgtloc)
+        grass.fatal(
+            _("Coordinate reference system not available for current location <%s>") %
+            tgtloc)
 
 
     # switch to temp location
     # switch to temp location
     os.environ['GISRC'] = str(SRCGISRC)
     os.environ['GISRC'] = str(SRCGISRC)
 
 
     # print projection at verbose level
     # print projection at verbose level
     grass.verbose(grass.read_command('g.proj', flags='p').rstrip(os.linesep))
     grass.verbose(grass.read_command('g.proj', flags='p').rstrip(os.linesep))
-    
+
     # make sure input is not xy
     # make sure input is not xy
     if grass.parse_command('g.proj', flags='g')['name'] == 'xy_location_unprojected':
     if grass.parse_command('g.proj', flags='g')['name'] == 'xy_location_unprojected':
         grass.fatal(_("Coordinate reference system not available for input <%s>") % OGRdatasource)
         grass.fatal(_("Coordinate reference system not available for input <%s>") % OGRdatasource)

+ 65 - 63
scripts/v.in.e00/v.in.e00.py

@@ -43,7 +43,7 @@ import shutil
 import glob
 import glob
 from grass.script.utils import try_rmdir, try_remove, basename
 from grass.script.utils import try_rmdir, try_remove, basename
 from grass.script import vector as gvect
 from grass.script import vector as gvect
-from grass.script import core as grass
+from grass.script import core as gcore
 from grass.exceptions import CalledModuleError
 from grass.exceptions import CalledModuleError
 
 
 
 
@@ -54,113 +54,115 @@ def main():
 
 
     e00tmp = str(os.getpid())
     e00tmp = str(os.getpid())
 
 
-    #### check for avcimport
-    if not grass.find_program('avcimport'):
-	grass.fatal(_("'avcimport' program not found, install it first") +
-		    "\n" +
-		    "http://avce00.maptools.org")
+    # check for avcimport
+    if not gcore.find_program('avcimport'):
+        gcore.fatal(_("'avcimport' program not found, install it first") +
+                    "\n" + "http://avce00.maptools.org")
 
 
-    #### check for e00conv
-    if not grass.find_program('e00conv'):
-	grass.fatal(_("'e00conv' program not found, install it first") +
-		    "\n" +
-		    "http://avce00.maptools.org")
+    # check for e00conv
+    if not gcore.find_program('e00conv'):
+        gcore.fatal(_("'e00conv' program not found, install it first") +
+                    "\n" + "http://avce00.maptools.org")
 
 
     # check that the user didn't use all three, which gets past the parser.
     # check that the user didn't use all three, which gets past the parser.
-    if type not in ['point','line','area']:
-	grass.fatal(_('Must specify one of "point", "line", or "area".'))
+    if type not in ['point', 'line', 'area']:
+        gcore.fatal(_('Must specify one of "point", "line", or "area".'))
 
 
     e00name = basename(filename, 'e00')
     e00name = basename(filename, 'e00')
     # avcimport only accepts 13 chars:
     # avcimport only accepts 13 chars:
     e00shortname = e00name[:13]
     e00shortname = e00name[:13]
 
 
-    #check if this is a split E00 file (.e01, .e02 ...):
+    # check if this is a split E00 file (.e01, .e02 ...):
     merging = False
     merging = False
     if os.path.exists(e00name + '.e01') or os.path.exists(e00name + '.E01'):
     if os.path.exists(e00name + '.e01') or os.path.exists(e00name + '.E01'):
-	grass.message(_("Found that E00 file is split into pieces (.e01, ...). Merging..."))
-	merging = True
+        gcore.message(_("Found that E00 file is split into pieces (.e01, ...)."
+                        " Merging..."))
+        merging = True
 
 
     if vect:
     if vect:
-	name = vect
+        name = vect
     else:
     else:
-	name = e00name
+        name = e00name
 
 
-    ### do import
+    # do import
 
 
-    #make a temporary directory
-    tmpdir = grass.tempfile()
+    # make a temporary directory
+    tmpdir = gcore.tempfile()
     try_remove(tmpdir)
     try_remove(tmpdir)
     os.mkdir(tmpdir)
     os.mkdir(tmpdir)
 
 
-    files = glob.glob(e00name + '.e[0-9][0-9]') + glob.glob(e00name + '.E[0-9][0-9]')
+    files = glob.glob(
+        e00name + '.e[0-9][0-9]') + glob.glob(e00name + '.E[0-9][0-9]')
     for f in files:
     for f in files:
-	shutil.copy(f, tmpdir)
+        shutil.copy(f, tmpdir)
 
 
-    #change to temporary directory to later avoid removal problems (rm -r ...)
+    # change to temporary directory to later avoid removal problems (rm -r ...)
     os.chdir(tmpdir)
     os.chdir(tmpdir)
 
 
-    #check for binay E00 file (we can just check if import fails):
-    #avcimport doesn't set exist status :-(
+    # check for binay E00 file (we can just check if import fails):
+    # avcimport doesn't set exist status :-(
 
 
     if merging:
     if merging:
-	files.sort()
-	filename = "%s.cat.%s.e00" % (e00name, e00tmp)
-	outf = file(filename, 'wb')
-	for f in files:
-	    inf = file(f, 'rb')
-	    shutil.copyfileobj(inf, outf)
-	    inf.close()
-	outf.close()
+        files.sort()
+        filename = "%s.cat.%s.e00" % (e00name, e00tmp)
+        outf = file(filename, 'wb')
+        for f in files:
+            inf = file(f, 'rb')
+            shutil.copyfileobj(inf, outf)
+            inf.close()
+        outf.close()
 
 
     nuldev = file(os.devnull, 'w+')
     nuldev = file(os.devnull, 'w+')
 
 
-    grass.message(_("An error may appear next which will be ignored..."))
-    if grass.call(['avcimport', filename, e00shortname], stdout = nuldev, stderr = nuldev) == 1:
-	grass.message(_("E00 ASCII found and converted to Arc Coverage in current directory"))
+    gcore.message(_("An error may appear next which will be ignored..."))
+    if gcore.call(['avcimport', filename, e00shortname], stdout=nuldev,
+                  stderr=nuldev) == 1:
+        gcore.message(_("E00 ASCII found and converted to Arc Coverage in "
+                        "current directory"))
     else:
     else:
-	grass.message(_("E00 Compressed ASCII found. Will uncompress first..."))
-	try_remove(e00shortname)
-	grass.call(['e00conv', filename, e00tmp + '.e00'])
-	grass.message(_("...converted to Arc Coverage in current directory"))
-	grass.call(['avcimport', e00tmp + '.e00', e00shortname], stderr = nuldev)
-
-    #SQL name fix:
+        gcore.message(
+            _("E00 Compressed ASCII found. Will uncompress first..."))
+        try_remove(e00shortname)
+        gcore.call(['e00conv', filename, e00tmp + '.e00'])
+        gcore.message(_("...converted to Arc Coverage in current directory"))
+        gcore.call(['avcimport', e00tmp + '.e00', e00shortname], stderr=nuldev)
+
+    # SQL name fix:
     name = name.replace('-', '_')
     name = name.replace('-', '_')
 
 
-    ## let's import...
-    grass.message(_("Importing %ss...") % type)
+    # let's import...
+    gcore.message(_("Importing %ss...") % type)
 
 
-    layer = dict(point = 'LAB', line = 'ARC', area = ['LAB','ARC'])
-    itype = dict(point = 'point', line = 'line', area = 'centroid')
+    layer = dict(point='LAB', line='ARC', area=['LAB', 'ARC'])
+    itype = dict(point='point', line='line', area='centroid')
 
 
     try:
     try:
-        grass.run_command('v.in.ogr', flags='o', input=e00shortname,
+        gcore.run_command('v.in.ogr', flags='o', input=e00shortname,
                           layer=layer[type], type=itype[type],
                           layer=layer[type], type=itype[type],
                           output=name)
                           output=name)
     except CalledModuleError:
     except CalledModuleError:
-        grass.fatal(_("An error occurred while running v.in.ogr"))
+        gcore.fatal(_("An error occurred while running v.in.ogr"))
 
 
-    grass.message(_("Imported <%s> vector map <%s>.") % (type, name))
+    gcore.message(_("Imported <%s> vector map <%s>.") % (type, name))
 
 
-    #### clean up the mess
+    # clean up the mess
     for root, dirs, files in os.walk('.', False):
     for root, dirs, files in os.walk('.', False):
-	for f in files:
-	    path = os.path.join(root, f)
-	    try_remove(path)
-	for d in dirs:
-	    path = os.path.join(root, d)
-	    try_rmdir(path)
+        for f in files:
+            path = os.path.join(root, f)
+            try_remove(path)
+        for d in dirs:
+            path = os.path.join(root, d)
+            try_rmdir(path)
 
 
     os.chdir('..')
     os.chdir('..')
     os.rmdir(tmpdir)
     os.rmdir(tmpdir)
-	
-    #### end
-    grass.message(_("Done."))
+
+    # end
+    gcore.message(_("Done."))
 
 
     # write cmd history:
     # write cmd history:
     gvect.vector_history(name)
     gvect.vector_history(name)
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gcore.parser()
     main()
     main()
-

+ 46 - 46
scripts/v.in.geonames/v.in.geonames.py

@@ -37,11 +37,12 @@
 import os
 import os
 import grass.script as grass
 import grass.script as grass
 
 
+
 def main():
 def main():
-    infile  = options['input']
+    infile = options['input']
     outfile = options['output']
     outfile = options['output']
-    
-    #are we in LatLong location?
+
+    # are we in LatLong location?
     s = grass.read_command("g.proj", flags='j')
     s = grass.read_command("g.proj", flags='j')
     kv = grass.parse_key_val(s)
     kv = grass.parse_key_val(s)
     if kv['+proj'] != 'longlat':
     if kv['+proj'] != 'longlat':
@@ -55,7 +56,8 @@ def main():
     kv = grass.db_connection()
     kv = grass.db_connection()
     dbfdriver = kv['driver'] == 'dbf'
     dbfdriver = kv['driver'] == 'dbf'
     if dbfdriver:
     if dbfdriver:
-        grass.warning(_("Since DBF driver is used, the content of the 'alternatenames' column might be cut with respect to the original Geonames.org column content"))
+        grass.warning(
+            _("Since DBF driver is used, the content of the 'alternatenames' column might be cut with respect to the original Geonames.org column content"))
 
 
     with open(infile) as f:
     with open(infile) as f:
         num_places = sum(1 for _ in f)
         num_places = sum(1 for _ in f)
@@ -87,55 +89,54 @@ def main():
 
 
     # geonameid|name|asciiname|alternatenames|latitude|longitude|featureclass|featurecode|countrycode|cc2|admin1code|admin2code|admin3code|admin4code|population|elevation|gtopo30|timezone|modificationdate
     # geonameid|name|asciiname|alternatenames|latitude|longitude|featureclass|featurecode|countrycode|cc2|admin1code|admin2code|admin3code|admin4code|population|elevation|gtopo30|timezone|modificationdate
 
 
-
     # debug:
     # debug:
     # head -n 3 ${TMPFILE}.csv
     # head -n 3 ${TMPFILE}.csv
 
 
     # use different column names limited to 10 chars for dbf
     # use different column names limited to 10 chars for dbf
     if dbfdriver:
     if dbfdriver:
         columns = ['geonameid integer',
         columns = ['geonameid integer',
-           'name varchar(200)',
-           'asciiname varchar(200)',
-           'altname varchar(4000)',
-           'latitude double precision',
-           'longitude double precision',
-           'featrclass varchar(1)',
-           'featrcode varchar(10)',
-           'cntrycode varchar(2)',
-           'cc2 varchar(60)',
-           'admin1code varchar(20)',
-           'admin2code varchar(20)',
-           'admin3code varchar(20)',
-           'admin4code varchar(20)',
-           'population integer',
-           'elevation integer',
-           'gtopo30 integer',
-           'timezone varchar(50)',
-           'mod_date date']
+                   'name varchar(200)',
+                   'asciiname varchar(200)',
+                   'altname varchar(4000)',
+                   'latitude double precision',
+                   'longitude double precision',
+                   'featrclass varchar(1)',
+                   'featrcode varchar(10)',
+                   'cntrycode varchar(2)',
+                   'cc2 varchar(60)',
+                   'admin1code varchar(20)',
+                   'admin2code varchar(20)',
+                   'admin3code varchar(20)',
+                   'admin4code varchar(20)',
+                   'population integer',
+                   'elevation integer',
+                   'gtopo30 integer',
+                   'timezone varchar(50)',
+                   'mod_date date']
     else:
     else:
         columns = ['geonameid integer',
         columns = ['geonameid integer',
-           'name varchar(200)',
-           'asciiname varchar(200)',
-           'alternatename varchar(4000)',
-           'latitude double precision',
-           'longitude double precision',
-           'featureclass varchar(1)',
-           'featurecode varchar(10)',
-           'countrycode varchar(2)',
-           'cc2 varchar(60)',
-           'admin1code varchar(20)',
-           'admin2code varchar(20)',
-           'admin3code varchar(20)',
-           'admin4code varchar(20)',
-           'population integer',
-           'elevation integer',
-           'gtopo30 integer',
-           'timezone varchar(50)',
-           'modification date']
-
-    grass.run_command('v.in.ascii', cat = 0, x = 6, y = 5, sep = 'tab',
-              input = infile, output = outfile,
-              columns = columns)
+                   'name varchar(200)',
+                   'asciiname varchar(200)',
+                   'alternatename varchar(4000)',
+                   'latitude double precision',
+                   'longitude double precision',
+                   'featureclass varchar(1)',
+                   'featurecode varchar(10)',
+                   'countrycode varchar(2)',
+                   'cc2 varchar(60)',
+                   'admin1code varchar(20)',
+                   'admin2code varchar(20)',
+                   'admin3code varchar(20)',
+                   'admin4code varchar(20)',
+                   'population integer',
+                   'elevation integer',
+                   'gtopo30 integer',
+                   'timezone varchar(50)',
+                   'modification date']
+
+    grass.run_command('v.in.ascii', cat=0, x=6, y=5, sep='tab',
+                      input=infile, output=outfile,
+                      columns=columns)
 
 
     # write cmd history:
     # write cmd history:
     grass.vector_history(outfile)
     grass.vector_history(outfile)
@@ -143,4 +144,3 @@ def main():
 if __name__ == "__main__":
 if __name__ == "__main__":
     options, flags = grass.parser()
     options, flags = grass.parser()
     main()
     main()
-

+ 6 - 9
scripts/v.in.lines/v.in.lines.py

@@ -41,9 +41,11 @@ import string
 from grass.script.utils import separator, try_remove
 from grass.script.utils import separator, try_remove
 from grass.script import core as grass
 from grass.script import core as grass
 
 
+
 def cleanup():
 def cleanup():
     try_remove(tmp)
     try_remove(tmp)
 
 
+
 def main():
 def main():
     global tmp
     global tmp
 
 
@@ -57,11 +59,9 @@ def main():
     else:
     else:
         do3D = ''
         do3D = ''
 
 
-
     tmp = grass.tempfile()
     tmp = grass.tempfile()
 
 
-
-    #### set up input file
+    # set up input file
     if options['input'] == '-':
     if options['input'] == '-':
         infile = None
         infile = None
         inf = sys.stdin
         inf = sys.stdin
@@ -71,7 +71,6 @@ def main():
             grass.fatal(_("Unable to read input file <%s>") % infile)
             grass.fatal(_("Unable to read input file <%s>") % infile)
         grass.debug("input file=[%s]" % infile)
         grass.debug("input file=[%s]" % infile)
 
 
-
     if not infile:
     if not infile:
         # read from stdin and write to tmpfile (v.in.mapgen wants a real file)
         # read from stdin and write to tmpfile (v.in.mapgen wants a real file)
         outf = file(tmp, 'w')
         outf = file(tmp, 'w')
@@ -99,8 +98,7 @@ def main():
             outf.close()
             outf.close()
             runfile = tmp
             runfile = tmp
 
 
-
-    ##### check that there are at least two columns (three if -z is given)
+    # check that there are at least two columns (three if -z is given)
     inf = file(runfile)
     inf = file(runfile)
     for line in inf:
     for line in inf:
         if len(line.lstrip()) == 0 or line[0] == '#':
         if len(line.lstrip()) == 0 or line[0] == '#':
@@ -111,9 +109,8 @@ def main():
     if (do3D and numcols < 3) or (not do3D and numcols < 2):
     if (do3D and numcols < 3) or (not do3D and numcols < 2):
         grass.fatal(_("Not enough data columns. (incorrect fs setting?)"))
         grass.fatal(_("Not enough data columns. (incorrect fs setting?)"))
 
 
-
-    grass.run_command('v.in.mapgen', flags = 'f' + do3D,
-                      input = runfile, output = options['output'])
+    grass.run_command('v.in.mapgen', flags='f' + do3D,
+                      input=runfile, output=options['output'])
 
 
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":

+ 28 - 28
scripts/v.in.mapgen/v.in.mapgen.py

@@ -34,7 +34,7 @@
 #%end
 #%end
 #%flag
 #%flag
 #% key: z
 #% key: z
-#% description: Create a 3D vector points map from 3 column Matlab data 
+#% description: Create a 3D vector points map from 3 column Matlab data
 #%end
 #%end
 #%option G_OPT_F_INPUT
 #%option G_OPT_F_INPUT
 #% description: Name of input file in Mapgen/Matlab format
 #% description: Name of input file in Mapgen/Matlab format
@@ -59,6 +59,7 @@ def cleanup():
     try_remove(tmp)
     try_remove(tmp)
     try_remove(tmp + '.dig')
     try_remove(tmp + '.dig')
 
 
+
 def main():
 def main():
     global tmp
     global tmp
 
 
@@ -89,32 +90,32 @@ def main():
 
 
     tmp = grass.tempfile()
     tmp = grass.tempfile()
 
 
-    #### create ascii vector file
+    # create ascii vector file
     inf = file(infile)
     inf = file(infile)
     outf = file(tmp, 'w')
     outf = file(tmp, 'w')
 
 
     grass.message(_("Importing data..."))
     grass.message(_("Importing data..."))
-    cat = 1   
+    cat = 1
     if matlab:
     if matlab:
-        ## HB:  OLD v.in.mapgen.sh Matlab import command follows.
-        ##    I have no idea what it's all about, so "new" matlab format will be
-        ##    a series of x y with "nan nan" breaking lines. (as NOAA provides)
-        ##  Old command:
+        # HB:  OLD v.in.mapgen.sh Matlab import command follows.
+        # I have no idea what it's all about, so "new" matlab format will be
+        # a series of x y with "nan nan" breaking lines. (as NOAA provides)
+        # Old command:
         #  tac $infile | $AWK 'BEGIN { FS="," ; R=0 }
         #  tac $infile | $AWK 'BEGIN { FS="," ; R=0 }
         #    $1~/\d*/   { printf("L %d\n", R) }
         #    $1~/\d*/   { printf("L %d\n", R) }
         #    $1~/   .*/ { printf(" %lf %lf\n", $2, $1) ; ++R }
         #    $1~/   .*/ { printf(" %lf %lf\n", $2, $1) ; ++R }
         #    $1~/END/   { }' | tac > "$TMP"
         #    $1~/END/   { }' | tac > "$TMP"
 
 
-        ## matlab format.
+        # matlab format.
         points = []
         points = []
- 
+
         for line in inf:
         for line in inf:
             f = line.split()
             f = line.split()
             if f[0].lower() == 'nan':
             if f[0].lower() == 'nan':
                 if points != []:
                 if points != []:
                     outf.write("L %d 1\n" % len(points))
                     outf.write("L %d 1\n" % len(points))
                     for point in points:
                     for point in points:
-                        outf.write(" %.15g %.15g %.15g\n" % tuple(map(float,point)))
+                        outf.write(" %.15g %.15g %.15g\n" % tuple(map(float, point)))
                     outf.write(" 1 %d\n" % cat)
                     outf.write(" 1 %d\n" % cat)
                     cat += 1
                     cat += 1
                 points = []
                 points = []
@@ -122,7 +123,7 @@ def main():
                 if len(f) == 2:
                 if len(f) == 2:
                     f.append('0')
                     f.append('0')
                 points.append(f)
                 points.append(f)
-        
+
         if points != []:
         if points != []:
             outf.write("L %d 1\n" % len(points))
             outf.write("L %d 1\n" % len(points))
             for point in points:
             for point in points:
@@ -131,36 +132,36 @@ def main():
                 except ValueError:
                 except ValueError:
                     grass.fatal(_("An error occurred on line '%s', exiting.") % line.strip())
                     grass.fatal(_("An error occurred on line '%s', exiting.") % line.strip())
             outf.write(" 1 %d\n" % cat)
             outf.write(" 1 %d\n" % cat)
-            cat += 1       
+            cat += 1
     else:
     else:
-        ## mapgen format.
+        # mapgen format.
         points = []
         points = []
         for line in inf:
         for line in inf:
             if line[0] == '#':
             if line[0] == '#':
                 if points != []:
                 if points != []:
                     outf.write("L %d 1\n" % len(points))
                     outf.write("L %d 1\n" % len(points))
                     for point in points:
                     for point in points:
-                        outf.write(" %.15g %.15g\n" % tuple(map(float,point)))
+                        outf.write(" %.15g %.15g\n" % tuple(map(float, point)))
                     outf.write(" 1 %d\n" % cat)
                     outf.write(" 1 %d\n" % cat)
                     cat += 1
                     cat += 1
                 points = []
                 points = []
             else:
             else:
                 points.append(line.rstrip('\r\n').split('\t'))
                 points.append(line.rstrip('\r\n').split('\t'))
-        
+
         if points != []:
         if points != []:
             outf.write("L %d 1\n" % len(points))
             outf.write("L %d 1\n" % len(points))
             for point in points:
             for point in points:
-                outf.write(" %.15g %.15g\n" % tuple(map(float,point)))
+                outf.write(" %.15g %.15g\n" % tuple(map(float, point)))
             outf.write(" 1 %d\n" % cat)
             outf.write(" 1 %d\n" % cat)
             cat += 1
             cat += 1
     outf.close()
     outf.close()
     inf.close()
     inf.close()
 
 
-    #### create digit header
+    # create digit header
     digfile = tmp + '.dig'
     digfile = tmp + '.dig'
     outf = file(digfile, 'w')
     outf = file(digfile, 'w')
-    t = string.Template(\
-"""ORGANIZATION: GRASSroots organization
+    t = string.Template(
+        """ORGANIZATION: GRASSroots organization
 DIGIT DATE:   $date
 DIGIT DATE:   $date
 DIGIT NAME:   $user@$host
 DIGIT NAME:   $user@$host
 MAP NAME:     $name
 MAP NAME:     $name
@@ -175,12 +176,12 @@ VERTI:
     year = time.strftime("%Y")
     year = time.strftime("%Y")
     user = os.getenv('USERNAME') or os.getenv('LOGNAME')
     user = os.getenv('USERNAME') or os.getenv('LOGNAME')
     host = os.getenv('COMPUTERNAME') or os.uname()[1]
     host = os.getenv('COMPUTERNAME') or os.uname()[1]
-    
-    s = t.substitute(prog = prog, name = name, date = date, year = year,
-                     user = user, host = host)
+
+    s = t.substitute(prog=prog, name=name, date=date, year=year,
+                     user=user, host=host)
     outf.write(s)
     outf.write(s)
-    
-    #### process points list to ascii vector file (merge in vertices)
+
+    # process points list to ascii vector file (merge in vertices)
     inf = file(tmp)
     inf = file(tmp)
     shutil.copyfileobj(inf, outf)
     shutil.copyfileobj(inf, outf)
     inf.close()
     inf.close()
@@ -188,13 +189,13 @@ VERTI:
     outf.close()
     outf.close()
 
 
     if not name:
     if not name:
-        #### if no name for vector file given, cat to stdout
+        # if no name for vector file given, cat to stdout
         inf = file(digfile)
         inf = file(digfile)
         shutil.copyfileobj(inf, sys.stdout)
         shutil.copyfileobj(inf, sys.stdout)
         inf.close()
         inf.close()
     else:
     else:
-        #### import to binary vector file
-        grass.message(_("Importing with v.in.ascii...")) 
+        # import to binary vector file
+        grass.message(_("Importing with v.in.ascii..."))
         try:
         try:
             grass.run_command('v.in.ascii', flags=do3D, input=digfile,
             grass.run_command('v.in.ascii', flags=do3D, input=digfile,
                               output=name, format='standard')
                               output=name, format='standard')
@@ -205,4 +206,3 @@ if __name__ == "__main__":
     options, flags = grass.parser()
     options, flags = grass.parser()
     atexit.register(cleanup)
     atexit.register(cleanup)
     main()
     main()
-

+ 7 - 7
scripts/v.in.wfs/v.in.wfs.py

@@ -64,7 +64,7 @@
 #%end
 #%end
 #%flag
 #%flag
 #% key: l
 #% key: l
-#todo #% description: List available layers and exit
+# todo #% description: List available layers and exit
 #% description: Download server capabilities to 'wms_capabilities.xml' in the current directory and exit
 #% description: Download server capabilities to 'wms_capabilities.xml' in the current directory and exit
 #% suppress_required: yes
 #% suppress_required: yes
 #%end
 #%end
@@ -80,6 +80,7 @@ from grass.script.utils import try_remove
 from grass.script import core as grass
 from grass.script import core as grass
 import urllib
 import urllib
 
 
+
 def main():
 def main():
     out = options['output']
     out = options['output']
     wfs_url = options['url']
     wfs_url = options['url']
@@ -104,7 +105,7 @@ def main():
             grass.fatal('Features begin with index "1"')
             grass.fatal('Features begin with index "1"')
 
 
     if flags['r']:
     if flags['r']:
-        bbox = grass.read_command("g.region", flags = 'w').split('=')[1]
+        bbox = grass.read_command("g.region", flags='w').split('=')[1]
         wfs_url += '&BBOX=' + bbox
         wfs_url += '&BBOX=' + bbox
 
 
     if flags['l']:
     if flags['l']:
@@ -119,10 +120,10 @@ def main():
     inf = urllib.urlopen(wfs_url)
     inf = urllib.urlopen(wfs_url)
     outf = file(tmpxml, 'wb')
     outf = file(tmpxml, 'wb')
     while True:
     while True:
-	s = inf.read()
-	if not s:
-	    break
-	outf.write(s)
+        s = inf.read()
+        if not s:
+            break
+        outf.write(s)
     inf.close()
     inf.close()
     outf.close()
     outf.close()
 
 
@@ -135,7 +136,6 @@ def main():
         try_remove(tmpxml)
         try_remove(tmpxml)
         sys.exit(0)
         sys.exit(0)
 
 
-
     grass.message(_("Importing data..."))
     grass.message(_("Importing data..."))
     try:
     try:
         grass.run_command('v.in.ogr', flags='o', input=tmpxml, output=out)
         grass.run_command('v.in.ogr', flags='o', input=tmpxml, output=out)

+ 154 - 138
scripts/v.krige/v.krige.py

@@ -15,7 +15,7 @@ License (>=v2). Read the file COPYING that comes with GRASS
 for details.
 for details.
 """
 """
 
 
-## g.parser information
+# g.parser information
 
 
 #%module
 #%module
 #% description: Performs ordinary or block kriging for vector maps.
 #% description: Performs ordinary or block kriging for vector maps.
@@ -96,27 +96,26 @@ for details.
 #% description: If omitted, will be <input name>_kriging.var
 #% description: If omitted, will be <input name>_kriging.var
 #% required : no
 #% required : no
 #%end
 #%end
+from __future__ import print_function
+import os
+import sys
 
 
-import os, sys
-from tempfile import gettempdir
-import time
-import thread
+# i18N
+import gettext
 
 
-if not os.environ.has_key("GISBASE"):
-    print "You must be in GRASS GIS to run this program."
+if "GISBASE" not in os.environ:
+    print("You must be in GRASS GIS to run this program.")
     sys.exit(1)
     sys.exit(1)
 
 
-### i18N
-import gettext
-gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
+gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'))
 
 
-### dependencies to be checked once, as they are quite time-consuming. cfr. grass.parser.
+# dependencies to be checked once, as they are quite time-consuming. cfr. grass.parser.
 # GRASS binding
 # GRASS binding
 try:
 try:
     import grass.script as grass
     import grass.script as grass
 except ImportError:
 except ImportError:
     sys.exit(_("No GRASS-python library found"))
     sys.exit(_("No GRASS-python library found"))
-    
+
 # move other checks in functions, as R?
 # move other checks in functions, as R?
 
 
 # globals
 # globals
@@ -128,12 +127,15 @@ except ImportError:
 #~ robjects = None
 #~ robjects = None
 #~ rinterface = None
 #~ rinterface = None
 
 
-#classes in alphabetical order. methods in logical order :)
+# classes in alphabetical order. methods in logical order :)
+
+# <2.5 class definition, without () - please test
+
 
 
-# <2.5 class definition, without () - please test 
 class Controller:
 class Controller:
     """ Executes analysis. For the moment, only with gstat functions."""
     """ Executes analysis. For the moment, only with gstat functions."""
     # moved here the global variables
     # moved here the global variables
+
     def __init__(self):
     def __init__(self):
         #~ self.Command = None
         #~ self.Command = None
         self.InputData = None
         self.InputData = None
@@ -141,24 +143,24 @@ class Controller:
         #~ VariogramFunction = None
         #~ VariogramFunction = None
         #~ robjects = None
         #~ robjects = None
         #~ rinterface = None
         #~ rinterface = None
-    
+
     def ImportMap(self, map, column):
     def ImportMap(self, map, column):
         """ Imports GRASS map as SpatialPointsDataFrame and adds x/y columns to attribute table.
         """ Imports GRASS map as SpatialPointsDataFrame and adds x/y columns to attribute table.
         Checks for NULL values in the provided column and exits if they are present."""
         Checks for NULL values in the provided column and exits if they are present."""
 
 
         #@NOTE: new way with R - as it doesn't alter original data
         #@NOTE: new way with R - as it doesn't alter original data
-        Rpointmap = robjects.r.readVECT(map, type =  'point')
+        Rpointmap = robjects.r.readVECT(map, type='point')
         # checks if x,y columns are present in dataframe. If they do are present, but with different names,
         # checks if x,y columns are present in dataframe. If they do are present, but with different names,
         # they'll be duplicated.
         # they'll be duplicated.
-        if "x" not in robjects.r.names(Rpointmap): 
+        if "x" not in robjects.r.names(Rpointmap):
             # extract coordinates with S4 method
             # extract coordinates with S4 method
             coordinatesPreDF = robjects.r['as.data.frame'](robjects.r.coordinates(Rpointmap))
             coordinatesPreDF = robjects.r['as.data.frame'](robjects.r.coordinates(Rpointmap))
-            coordinatesDF = robjects.r['data.frame'](x = coordinatesPreDF.rx('coords.x1')[0],
-                                                     y = coordinatesPreDF.rx('coords.x2')[0])
+            coordinatesDF = robjects.r['data.frame'](x=coordinatesPreDF.rx('coords.x1')[0],
+                                                     y=coordinatesPreDF.rx('coords.x2')[0])
             # match coordinates with data slot of SpatialPointsDataFrame - maptools function
             # match coordinates with data slot of SpatialPointsDataFrame - maptools function
             # match is done on row.names
             # match is done on row.names
             Rpointmap = robjects.r.spCbind(Rpointmap, coordinatesDF)
             Rpointmap = robjects.r.spCbind(Rpointmap, coordinatesDF)
-            
+
         # GRASS checks for null values in the chosen column. R can hardly handle column as a variable,
         # GRASS checks for null values in the chosen column. R can hardly handle column as a variable,
         # looks for a hardcoded string.
         # looks for a hardcoded string.
         cols = grass.vector_columns(map=map, layer=1)
         cols = grass.vector_columns(map=map, layer=1)
@@ -166,95 +168,101 @@ class Controller:
                                         map=map,
                                         map=map,
                                         column=column,
                                         column=column,
                                         type='point',
                                         type='point',
-                                        parse = (grass.parse_key_val,
-                                                 {'sep':': '}
-                                                 )
+                                        parse=(grass.parse_key_val,
+                                               {'sep': ': '}
+                                               )
                                         )['number of NULL attributes'])
                                         )['number of NULL attributes'])
-        if nulls > 0: 
-            grass.fatal(_("%d NULL value(s) in the selected column - unable to perform kriging.") % nulls)
+        if nulls > 0:
+            grass.fatal(
+                _("%d NULL value(s) in the selected column - unable to perform kriging.") %
+                nulls)
         return Rpointmap
         return Rpointmap
-    
+
     def CreateGrid(self, inputdata):
     def CreateGrid(self, inputdata):
         Region = grass.region()
         Region = grass.region()
         Grid = robjects.r.gmeta2grd()
         Grid = robjects.r.gmeta2grd()
 
 
         # addition of coordinates columns into dataframe.
         # addition of coordinates columns into dataframe.
         coordinatesDF = robjects.r['as.data.frame'](robjects.r.coordinates(Grid))
         coordinatesDF = robjects.r['as.data.frame'](robjects.r.coordinates(Grid))
-        data = robjects.r['data.frame'](x = coordinatesDF.rx('s1')[0],
-                                        y = coordinatesDF.rx('s2')[0],
-                                        k = robjects.r.rep(1, Region['cols']*Region['rows']))
-        GridPredicted = robjects.r.SpatialGridDataFrame(Grid,
-                                                        data,
-                                                        proj4string =  robjects.r.CRS(robjects.r.proj4string(inputdata)))
+        data = robjects.r['data.frame'](x=coordinatesDF.rx('s1')[0],
+                                        y=coordinatesDF.rx('s2')[0],
+                                        k=robjects.r.rep(1, Region['cols'] * Region['rows']))
+        GridPredicted = robjects.r.SpatialGridDataFrame(
+            Grid, data, proj4string=robjects.r.CRS(
+                robjects.r.proj4string(inputdata)))
         return GridPredicted
         return GridPredicted
-    
+
     def ComposeFormula(self, column, isblock):
     def ComposeFormula(self, column, isblock):
         if isblock is True:
         if isblock is True:
             predictor = 'x+y'
             predictor = 'x+y'
         else:
         else:
             predictor = '1'
             predictor = '1'
-        print column + "~" + predictor
+        print(column + "~" + predictor)
         Formula = robjects.Formula(column + "~" + predictor)
         Formula = robjects.Formula(column + "~" + predictor)
         return Formula
         return Formula
-    
-    def FitVariogram(self, formula, inputdata, sill, nugget, range, kappa, model = ''):
+
+    def FitVariogram(self, formula, inputdata, sill, nugget, range, kappa, model=''):
         """ Fits variogram either automagically either specifying all parameters.
         """ Fits variogram either automagically either specifying all parameters.
         Returns a list containing data and model variograms. """
         Returns a list containing data and model variograms. """
-        
+
         Variograms = {}
         Variograms = {}
-        
+
         if model is '':
         if model is '':
             robjects.r.require('automap')
             robjects.r.require('automap')
             DottedParams = {}
             DottedParams = {}
             #print (nugget.r_repr(), sill, range)
             #print (nugget.r_repr(), sill, range)
             DottedParams['fix.values'] = robjects.r.c(nugget, range, sill)
             DottedParams['fix.values'] = robjects.r.c(nugget, range, sill)
-            
-            if not type(kappa) == float:
+
+            if not isinstance(kappa, float):
                 # autofit gives strange results if kappa is NA
                 # autofit gives strange results if kappa is NA
                 VariogramModel = robjects.r.autofitVariogram(formula, inputdata, **DottedParams)
                 VariogramModel = robjects.r.autofitVariogram(formula, inputdata, **DottedParams)
             else:
             else:
-                VariogramModel = robjects.r.autofitVariogram(formula, inputdata, kappa=kappa, **DottedParams)
-            #print robjects.r.warnings()
+                VariogramModel = robjects.r.autofitVariogram(
+                    formula, inputdata, kappa=kappa, **DottedParams)
+            # print robjects.r.warnings()
             Variograms['datavariogram'] = VariogramModel.rx('exp_var')[0]
             Variograms['datavariogram'] = VariogramModel.rx('exp_var')[0]
             Variograms['variogrammodel'] = VariogramModel.rx('var_model')[0]
             Variograms['variogrammodel'] = VariogramModel.rx('var_model')[0]
-            # obtain the model name. *Too* complicated to get the string instead of level, unlike R does.
-            VariogramAsDF = robjects.r['as.data.frame'](VariogramModel.rx('var_model')[0]) # force conversion
+            # obtain the model name. *Too* complicated to get the string instead of
+            # level, unlike R does.
+            VariogramAsDF = robjects.r['as.data.frame'](
+                VariogramModel.rx('var_model')[0])  # force conversion
             ModelDF = VariogramAsDF.rx('model')[0]
             ModelDF = VariogramAsDF.rx('model')[0]
             Variograms['model'] = ModelDF.levels[ModelDF[1] - 1]
             Variograms['model'] = ModelDF.levels[ModelDF[1] - 1]
         else:
         else:
             DataVariogram = robjects.r['variogram'](formula, inputdata)
             DataVariogram = robjects.r['variogram'](formula, inputdata)
             VariogramModel = robjects.r['fit.variogram'](DataVariogram,
             VariogramModel = robjects.r['fit.variogram'](DataVariogram,
-                                                         model = robjects.r.vgm(psill = sill,
-                                                                                model = model,
-                                                                                nugget = nugget,
-                                                                                range = range,
-                                                                                kappa = kappa))
+                                                         model=robjects.r.vgm(psill=sill,
+                                                                              model=model,
+                                                                              nugget=nugget,
+                                                                              range=range,
+                                                                              kappa=kappa))
             Variograms['datavariogram'] = DataVariogram
             Variograms['datavariogram'] = DataVariogram
             Variograms['variogrammodel'] = VariogramModel
             Variograms['variogrammodel'] = VariogramModel
             Variograms['model'] = model
             Variograms['model'] = model
         return Variograms
         return Variograms
-    
+
     def DoKriging(self, formula, inputdata, grid, model, block):
     def DoKriging(self, formula, inputdata, grid, model, block):
-        DottedParams = {'debug.level': -1} # let krige() print percentage status
-        if block is not '': #@FIXME(anne): but it's a string!! and krige accepts it!!
+        DottedParams = {'debug.level': -1}  # let krige() print percentage status
+        if block is not '':  # @FIXME(anne): but it's a string!! and krige accepts it!!
             DottedParams['block'] = block
             DottedParams['block'] = block
-        #print DottedParams
+        # print DottedParams
         KrigingResult = robjects.r.krige(formula, inputdata, grid, model, **DottedParams)
         KrigingResult = robjects.r.krige(formula, inputdata, grid, model, **DottedParams)
         return KrigingResult
         return KrigingResult
- 
+
     def ExportMap(self, map, column, name, overwrite, command, variograms):
     def ExportMap(self, map, column, name, overwrite, command, variograms):
         # add kriging parameters to raster map history
         # add kriging parameters to raster map history
-        robjects.r.writeRAST(map, vname = name, zcol = column, overwrite = overwrite)
+        robjects.r.writeRAST(map, vname=name, zcol=column, overwrite=overwrite)
         grass.run_command('r.support',
         grass.run_command('r.support',
-                          map = name,
-                          title = 'Kriging output',
-                          history = 'Issued from command v.krige ' + command)
-        if command.find('model') is -1: # if the command has no model option, add automap chosen model
-                    grass.run_command('r.support',
-                                      map = name,
-                                      history = 'Model chosen by automatic fitting: ' + variograms['model'])
-        
-    def Run(self, input, column, output, package, sill, nugget, range, kappa, logger, \
+                          map=name,
+                          title='Kriging output',
+                          history='Issued from command v.krige ' + command)
+        if command.find(
+                'model') is -1:  # if the command has no model option, add automap chosen model
+            grass.run_command('r.support',
+                              map=name,
+                              history='Model chosen by automatic fitting: ' + variograms['model'])
+
+    def Run(self, input, column, output, package, sill, nugget, range, kappa, logger,
             overwrite, model, block, output_var, command, **kwargs):
             overwrite, model, block, output_var, command, **kwargs):
         """ Wrapper for all functions above. """
         """ Wrapper for all functions above. """
 
 
@@ -267,9 +275,9 @@ class Controller:
         # and from here over, InputData refers to the global variable
         # and from here over, InputData refers to the global variable
         #print(robjects.r.slot(InputData, 'data').names)
         #print(robjects.r.slot(InputData, 'data').names)
         logger.message(_("Data successfully imported."))
         logger.message(_("Data successfully imported."))
-        
+
         GridPredicted = self.CreateGrid(self.InputData)
         GridPredicted = self.CreateGrid(self.InputData)
-        
+
         logger.message(_("Fitting variogram..."))
         logger.message(_("Fitting variogram..."))
 
 
         if block is not '':
         if block is not '':
@@ -278,87 +286,93 @@ class Controller:
             self.predictor = '1'
             self.predictor = '1'
         if self.Variogram is None:
         if self.Variogram is None:
             self.Variogram = self.FitVariogram(robjects.Formula(column + "~" + self.predictor),
             self.Variogram = self.FitVariogram(robjects.Formula(column + "~" + self.predictor),
-                                          self.InputData,
-                                          model = model,
-                                          sill = sill,
-                                          nugget = nugget,
-                                          range = range,
-                                          kappa = kappa)
+                                               self.InputData,
+                                               model=model,
+                                               sill=sill,
+                                               nugget=nugget,
+                                               range=range,
+                                               kappa=kappa)
         logger.message(_("Variogram fitting complete."))
         logger.message(_("Variogram fitting complete."))
-        
+
         logger.message(_("Kriging..."))
         logger.message(_("Kriging..."))
-        KrigingResult = self.DoKriging(robjects.Formula(column + "~" + self.predictor), self.InputData,
-                 GridPredicted, self.Variogram['variogrammodel'], block) # using global ones
+        KrigingResult = self.DoKriging(
+            robjects.Formula(
+                column + "~" + self.predictor),
+            self.InputData,
+            GridPredicted,
+            self.Variogram['variogrammodel'],
+            block)  # using global ones
         logger.message(_("Kriging complete."))
         logger.message(_("Kriging complete."))
-        
-        self.ExportMap(map = KrigingResult,
+
+        self.ExportMap(map=KrigingResult,
                        column='var1.pred',
                        column='var1.pred',
-                       name = output,
-                       overwrite = overwrite,
-                       command = command,
-                       variograms = self.Variogram)
+                       name=output,
+                       overwrite=overwrite,
+                       command=command,
+                       variograms=self.Variogram)
         if output_var is not '':
         if output_var is not '':
-            self.ExportMap(map = KrigingResult,
+            self.ExportMap(map=KrigingResult,
                            column='var1.var',
                            column='var1.var',
-                           name = output_var,
-                           overwrite = overwrite,
-                           command = command,
-                           variograms = self.Variogram)
-        
-def main(argv = None):
+                           name=output_var,
+                           overwrite=overwrite,
+                           command=command,
+                           variograms=self.Variogram)
+
+
+def main(argv=None):
     """ Main. Calls either GUI or CLI, depending on arguments provided. """
     """ Main. Calls either GUI or CLI, depending on arguments provided. """
     #@FIXME: solve this double ifelse. the control should not be done twice.
     #@FIXME: solve this double ifelse. the control should not be done twice.
-    
+
     controller = Controller()
     controller = Controller()
-    
+
     if argv is None:
     if argv is None:
         importR()
         importR()
-        argv = sys.argv[1:] # stripping first item, the full name of this script
+        argv = sys.argv[1:]  # stripping first item, the full name of this script
         # wxGUI call
         # wxGUI call
         if not os.getenv("GRASS_WXBUNDLED"):
         if not os.getenv("GRASS_WXBUNDLED"):
             from core import globalvar
             from core import globalvar
             globalvar.CheckForWx()
             globalvar.CheckForWx()
         from modules import vkrige as GUI
         from modules import vkrige as GUI
-        
+
         import wx
         import wx
-        
+
         app = wx.App()
         app = wx.App()
-        KrigingFrame = GUI.KrigingModule(parent = None,
-                                         Rinstance = robjects,
-                                         controller = controller)
+        KrigingFrame = GUI.KrigingModule(parent=None,
+                                         Rinstance=robjects,
+                                         controller=controller)
         KrigingFrame.Centre()
         KrigingFrame.Centre()
         KrigingFrame.Show()
         KrigingFrame.Show()
         app.MainLoop()
         app.MainLoop()
-        
+
     else:
     else:
-        #CLI
+        # CLI
         options, flags = argv
         options, flags = argv
-        
+
         #@TODO: Work on verbosity. Sometimes it's too verbose (R), sometimes not enough.
         #@TODO: Work on verbosity. Sometimes it's too verbose (R), sometimes not enough.
-        if grass.find_file(options['input'], element = 'vector')['fullname'] is '':
-            grass.fatal(_("Vector map <%s> not found") % options['input'] )
-        
+        if grass.find_file(options['input'], element='vector')['fullname'] is '':
+            grass.fatal(_("Vector map <%s> not found") % options['input'])
+
         #@TODO: elaborate input string, if contains mapset or not.. thanks again to Bob for testing on 64bit.
         #@TODO: elaborate input string, if contains mapset or not.. thanks again to Bob for testing on 64bit.
-        
+
         # create output map name, if not specified
         # create output map name, if not specified
         if options['output'] is '':
         if options['output'] is '':
-            try: # to strip mapset name from fullname. Ugh.
+            try:  # to strip mapset name from fullname. Ugh.
                 options['input'] = options['input'].split("@")[0]
                 options['input'] = options['input'].split("@")[0]
             except:
             except:
                 pass
                 pass
             options['output'] = options['input'] + '_kriging'
             options['output'] = options['input'] + '_kriging'
 
 
         # check for output map with same name. g.parser can't handle this, afaik.
         # check for output map with same name. g.parser can't handle this, afaik.
-        if grass.find_file(options['output'], element = 'cell')['fullname'] \
-           and os.getenv("GRASS_OVERWRITE") == None:
+        if grass.find_file(options['output'], element='cell')['fullname'] \
+           and os.getenv("GRASS_OVERWRITE") is None:
             grass.fatal(_("option: <output>: Raster map already exists."))
             grass.fatal(_("option: <output>: Raster map already exists."))
 
 
         if options['output_var'] is not '' \
         if options['output_var'] is not '' \
-           and (grass.find_file(options['output_var'], element = 'cell')['fullname'] \
-           and os.getenv("GRASS_OVERWRITE") == None):
+           and (grass.find_file(options['output_var'], element='cell')['fullname']
+                and os.getenv("GRASS_OVERWRITE") is None):
             grass.fatal(_("option: <output>: Variance raster map already exists."))
             grass.fatal(_("option: <output>: Variance raster map already exists."))
 
 
-        importR()        
+        importR()
         if options['model'] is '':
         if options['model'] is '':
             try:
             try:
                 robjects.r.require("automap")
                 robjects.r.require("automap")
@@ -366,19 +380,20 @@ def main(argv = None):
                 grass.fatal(_("R package automap is missing, no variogram autofit available."))
                 grass.fatal(_("R package automap is missing, no variogram autofit available."))
         else:
         else:
             if options['sill'] is '' or options['nugget'] is '' or options['range'] is '':
             if options['sill'] is '' or options['nugget'] is '' or options['range'] is '':
-                grass.fatal(_("You have specified model, but forgot at least one of sill, nugget and range."))
-        
+                grass.fatal(
+                    _("You have specified model, but forgot at least one of sill, nugget and range."))
+
         #@TODO: let GRASS remount its commandstring. Until then, keep that 4 lines below.
         #@TODO: let GRASS remount its commandstring. Until then, keep that 4 lines below.
-        #print grass.write_command(argv)
+        # print grass.write_command(argv)
         command = ""
         command = ""
         notnulloptions = {}
         notnulloptions = {}
         for k, v in options.items():
         for k, v in options.items():
             if v is not '':
             if v is not '':
                 notnulloptions[k] = v
                 notnulloptions[k] = v
         command = command.join("%s=%s " % (k, v) for k, v in notnulloptions.items())
         command = command.join("%s=%s " % (k, v) for k, v in notnulloptions.items())
-        
+
         # re-cast integers from strings, as parser() cast everything to string.
         # re-cast integers from strings, as parser() cast everything to string.
-        for each in ("sill","nugget","range","kappa"):
+        for each in ("sill", "nugget", "range", "kappa"):
             if options[each] is not '':
             if options[each] is not '':
                 if each == "kappa":
                 if each == "kappa":
                     options[each] = float(options[each])
                     options[each] = float(options[each])
@@ -386,23 +401,24 @@ def main(argv = None):
                     options[each] = int(options[each])
                     options[each] = int(options[each])
             else:
             else:
                 options[each] = robjects.r('''NA''')
                 options[each] = robjects.r('''NA''')
-        
+
         #controller = Controller()
         #controller = Controller()
-        controller.Run(input = options['input'],
-                       column = options['column'],
-                       output = options['output'],
-                       overwrite = os.getenv("GRASS_OVERWRITE") == 1,
-                       package = options['package'],
-                       model = options['model'],
-                       block = options['block'],
-                       sill = options['sill'],
-                       nugget = options['nugget'],
-                       range = options['range'],
-                       kappa = options['kappa'],
-                       output_var = options['output_var'],
-                       command = command,
-                       logger = grass)
-    
+        controller.Run(input=options['input'],
+                       column=options['column'],
+                       output=options['output'],
+                       overwrite=os.getenv("GRASS_OVERWRITE") == 1,
+                       package=options['package'],
+                       model=options['model'],
+                       block=options['block'],
+                       sill=options['sill'],
+                       nugget=options['nugget'],
+                       range=options['range'],
+                       kappa=options['kappa'],
+                       output_var=options['output_var'],
+                       command=command,
+                       logger=grass)
+
+
 def importR():
 def importR():
     # R
     # R
     # unuseful since rpy2 will complain adequately.
     # unuseful since rpy2 will complain adequately.
@@ -411,31 +427,31 @@ def importR():
     #    grass.find_program('R')
     #    grass.find_program('R')
     # except:
     # except:
     #    sys.exit(_("R is not installed. Install it and re-run, or modify environment variables."))
     #    sys.exit(_("R is not installed. Install it and re-run, or modify environment variables."))
-    
+
     # rpy2
     # rpy2
     global robjects
     global robjects
     global rinterface
     global rinterface
     grass.message(_('Loading dependencies, please wait...'))
     grass.message(_('Loading dependencies, please wait...'))
     try:
     try:
         import rpy2.robjects as robjects
         import rpy2.robjects as robjects
-        import rpy2.rinterface as rinterface #to speed up kriging? for plots.
+        import rpy2.rinterface as rinterface  # to speed up kriging? for plots.
     except ImportError:
     except ImportError:
         # ok for other OSes?
         # ok for other OSes?
         grass.fatal(_("Python module 'Rpy2' not found. Please install it and re-run v.krige."))
         grass.fatal(_("Python module 'Rpy2' not found. Please install it and re-run v.krige."))
-        
+
     # R packages check. Will create one error message after check of all packages.
     # R packages check. Will create one error message after check of all packages.
     missingPackagesList = []
     missingPackagesList = []
     for each in ["rgeos", "gstat", "rgrass7", "maptools"]:
     for each in ["rgeos", "gstat", "rgrass7", "maptools"]:
-        if not robjects.r.require(each, quietly = True)[0]:
+        if not robjects.r.require(each, quietly=True)[0]:
             missingPackagesList.append(each)
             missingPackagesList.append(each)
     if missingPackagesList:
     if missingPackagesList:
         errorString = _("R package(s) ") + \
         errorString = _("R package(s) ") + \
-                      ", ".join(map(str, missingPackagesList)) + \
-                      _(" missing. Install it/them and re-run v.krige.")
+            ", ".join(map(str, missingPackagesList)) + \
+            _(" missing. Install it/them and re-run v.krige.")
         grass.fatal(errorString)
         grass.fatal(errorString)
-    
+
 if __name__ == '__main__':
 if __name__ == '__main__':
     if len(sys.argv) > 1:
     if len(sys.argv) > 1:
-        sys.exit(main(argv = grass.parser()))
+        sys.exit(main(argv=grass.parser()))
     else:
     else:
         main()
         main()

+ 27 - 25
scripts/v.pack/v.pack.py

@@ -43,36 +43,38 @@ from grass.script.utils import try_rmdir, try_remove
 from grass.script import core as grass
 from grass.script import core as grass
 from grass.script import vector as vector
 from grass.script import vector as vector
 
 
+
 def cleanup():
 def cleanup():
     try_rmdir(basedir)
     try_rmdir(basedir)
 
 
+
 def main():
 def main():
     infile = options['input']
     infile = options['input']
     compression_off = flags['c']
     compression_off = flags['c']
-    
+
     global basedir
     global basedir
     basedir = grass.tempdir()
     basedir = grass.tempdir()
-    
+
     # check if vector map exists
     # check if vector map exists
-    gfile = grass.find_file(infile, element = 'vector')
+    gfile = grass.find_file(infile, element='vector')
     if not gfile['name']:
     if not gfile['name']:
         grass.fatal(_("Vector map <%s> not found") % infile)
         grass.fatal(_("Vector map <%s> not found") % infile)
-    
+
     # check if input vector map is in the native format
     # check if input vector map is in the native format
     if vector.vector_info(gfile['fullname'])['format'] != 'native':
     if vector.vector_info(gfile['fullname'])['format'] != 'native':
-        grass.fatal(_("Unable to pack vector map <%s>. Only native format supported.") % \
-                        gfile['fullname'])
-    
+        grass.fatal(_("Unable to pack vector map <%s>. Only native format supported.") %
+                    gfile['fullname'])
+
     # split the name if there is the mapset name
     # split the name if there is the mapset name
     if infile.find('@'):
     if infile.find('@'):
         infile = infile.split('@')[0]
         infile = infile.split('@')[0]
-    
+
     # output name
     # output name
     if options['output']:
     if options['output']:
         outfile = options['output']
         outfile = options['output']
     else:
     else:
         outfile = infile + '.pack'
         outfile = infile + '.pack'
-    
+
     # check if exists the output file
     # check if exists the output file
     if os.path.exists(outfile):
     if os.path.exists(outfile):
         if os.getenv('GRASS_OVERWRITE'):
         if os.getenv('GRASS_OVERWRITE'):
@@ -80,18 +82,18 @@ def main():
             try_remove(outfile)
             try_remove(outfile)
         else:
         else:
             grass.fatal(_("option <%s>: <%s> exists.") % ("output", outfile))
             grass.fatal(_("option <%s>: <%s> exists.") % ("output", outfile))
-    
+
     # prepare for packing
     # prepare for packing
     grass.verbose(_("Packing <%s>...") % (gfile['fullname']))
     grass.verbose(_("Packing <%s>...") % (gfile['fullname']))
-    
-    # write tar file, optional compression 
+
+    # write tar file, optional compression
     if compression_off:
     if compression_off:
-        tar = tarfile.open(name = outfile, mode = 'w:')
+        tar = tarfile.open(name=outfile, mode='w:')
     else:
     else:
-        tar = tarfile.open(name = outfile, mode = 'w:gz')
+        tar = tarfile.open(name=outfile, mode='w:gz')
     tar.add(gfile['file'], infile)
     tar.add(gfile['file'], infile)
-    
-    # check if exist a db connection for the vector 
+
+    # check if exist a db connection for the vector
     db_vect = vector.vector_db(gfile['fullname'])
     db_vect = vector.vector_db(gfile['fullname'])
     if not db_vect:
     if not db_vect:
         grass.verbose(_('There is not database connected with vector map <%s>') % gfile['fullname'])
         grass.verbose(_('There is not database connected with vector map <%s>') % gfile['fullname'])
@@ -99,14 +101,14 @@ def main():
         # for each layer connection save a table in sqlite database
         # for each layer connection save a table in sqlite database
         sqlitedb = os.path.join(basedir, 'db.sqlite')
         sqlitedb = os.path.join(basedir, 'db.sqlite')
         for i, dbconn in db_vect.iteritems():
         for i, dbconn in db_vect.iteritems():
-            grass.run_command('db.copy', from_driver = dbconn['driver'], 
-                              from_database = dbconn['database'],
-                              from_table =  dbconn['table'], 
-                              to_driver = 'sqlite', to_database = sqlitedb, 
-                              to_table = dbconn['table'])
+            grass.run_command('db.copy', from_driver=dbconn['driver'],
+                              from_database=dbconn['database'],
+                              from_table=dbconn['table'],
+                              to_driver='sqlite', to_database=sqlitedb,
+                              to_table=dbconn['table'])
         tar.add(sqlitedb, 'db.sqlite')
         tar.add(sqlitedb, 'db.sqlite')
-    
-    # add to the tar file the PROJ files to check when unpack file    
+
+    # add to the tar file the PROJ files to check when unpack file
     gisenv = grass.gisenv()
     gisenv = grass.gisenv()
     for support in ['INFO', 'UNITS', 'EPSG']:
     for support in ['INFO', 'UNITS', 'EPSG']:
         path = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'],
         path = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'],
@@ -114,9 +116,9 @@ def main():
         if os.path.exists(path):
         if os.path.exists(path):
             tar.add(path, 'PROJ_' + support)
             tar.add(path, 'PROJ_' + support)
     tar.close()
     tar.close()
-    
+
     grass.message(_("Pack file <%s> created") % os.path.join(os.getcwd(), outfile))
     grass.message(_("Pack file <%s> created") % os.path.join(os.getcwd(), outfile))
-            
+
 if __name__ == "__main__":
 if __name__ == "__main__":
     options, flags = grass.parser()
     options, flags = grass.parser()
     atexit.register(cleanup)
     atexit.register(cleanup)

+ 9 - 9
scripts/v.rast.stats/testsuite/test_v_rast_stats.py

@@ -5,6 +5,7 @@
 from grass.gunittest.case import TestCase
 from grass.gunittest.case import TestCase
 from grass.gunittest.gmodules import SimpleModule
 from grass.gunittest.gmodules import SimpleModule
 
 
+
 class TestRastStats(TestCase):
 class TestRastStats(TestCase):
 
 
     @classmethod
     @classmethod
@@ -36,19 +37,20 @@ class TestRastStats(TestCase):
 
 
     def test_1(self):
     def test_1(self):
         # Output of v.rast.stats
         # Output of v.rast.stats
-        univar_string="""cat|value|label|a_minimum|a_maximum|a_sum
+        univar_string = """cat|value|label|a_minimum|a_maximum|a_sum
 1|1||102|209|265905
 1|1||102|209|265905
 2|2||121|280|1281195
 2|2||121|280|1281195
 """
 """
-        
-        self.assertModule("v.rast.stats",  map="zone_map", raster="map_a",
-                          method=["minimum","maximum","sum"], flags="c",
+
+        self.assertModule("v.rast.stats", map="zone_map", raster="map_a",
+                          method=["minimum", "maximum", "sum"], flags="c",
                           column_prefix="a")
                           column_prefix="a")
         v_db_select = SimpleModule("v.db.select", map="zone_map")
         v_db_select = SimpleModule("v.db.select", map="zone_map")
-        
-        self.runModule(v_db_select)        
+
+        self.runModule(v_db_select)
         self.assertLooksLike(univar_string, v_db_select.outputs.stdout)
         self.assertLooksLike(univar_string, v_db_select.outputs.stdout)
 
 
+
 class TestRastStatsFails(TestCase):
 class TestRastStatsFails(TestCase):
 
 
     def test_error_handling_a(self):
     def test_error_handling_a(self):
@@ -60,7 +62,7 @@ class TestRastStatsFails(TestCase):
         # No raster map
         # No raster map
         self.assertModuleFail("v.rast.stats", map="zone_map",
         self.assertModuleFail("v.rast.stats", map="zone_map",
                               column_prefix="a")
                               column_prefix="a")
-        
+
     def test_error_handling_d(self):
     def test_error_handling_d(self):
         # No column_prefix
         # No column_prefix
         self.assertModuleFail("v.rast.stats", map="zone_map", raster="map_b")
         self.assertModuleFail("v.rast.stats", map="zone_map", raster="map_b")
@@ -68,5 +70,3 @@ class TestRastStatsFails(TestCase):
 if __name__ == '__main__':
 if __name__ == '__main__':
     from grass.gunittest.main import test
     from grass.gunittest.main import test
     test()
     test()
-
-

+ 9 - 5
scripts/v.rast.stats/v.rast.stats.py

@@ -79,7 +79,7 @@ def cleanup():
 def main():
 def main():
     global tmp, sqltmp, tmpname, nuldev, vector, rastertmp
     global tmp, sqltmp, tmpname, nuldev, vector, rastertmp
     rastertmp = False
     rastertmp = False
-    #### setup temporary files
+    # setup temporary files
     tmp = grass.tempfile()
     tmp = grass.tempfile()
     sqltmp = tmp + ".sql"
     sqltmp = tmp + ".sql"
     # we need a random name
     # we need a random name
@@ -146,13 +146,15 @@ def main():
     try:
     try:
         fi = grass.vector_db(map=vector)[int(layer)]
         fi = grass.vector_db(map=vector)[int(layer)]
     except KeyError:
     except KeyError:
-        grass.fatal(_('There is no table connected to this map. Run v.db.connect or v.db.addtable first.'))
+        grass.fatal(
+            _('There is no table connected to this map. Run v.db.connect or v.db.addtable first.'))
     # we need this for non-DBF driver:
     # we need this for non-DBF driver:
     dbfdriver = fi['driver'] == 'dbf'
     dbfdriver = fi['driver'] == 'dbf'
 
 
     # Find out which table is linked to the vector map on the given layer
     # Find out which table is linked to the vector map on the given layer
     if not fi['table']:
     if not fi['table']:
-        grass.fatal(_('There is no table connected to this map. Run v.db.connect or v.db.addtable first.'))
+        grass.fatal(
+            _('There is no table connected to this map. Run v.db.connect or v.db.addtable first.'))
 
 
     # replaced by user choiche
     # replaced by user choiche
     #basecols = ['n', 'min', 'max', 'range', 'mean', 'stddev', 'variance', 'cf_var', 'sum']
     #basecols = ['n', 'min', 'max', 'range', 'mean', 'stddev', 'variance', 'cf_var', 'sum']
@@ -206,7 +208,7 @@ def main():
         if currcolumn in grass.vector_columns(vector, layer).keys():
         if currcolumn in grass.vector_columns(vector, layer).keys():
             if not flags['c']:
             if not flags['c']:
                 grass.fatal((_("Cannot create column <%s> (already present). ") % currcolumn) +
                 grass.fatal((_("Cannot create column <%s> (already present). ") % currcolumn) +
-                             _("Use -c flag to update values in this column."))
+                            _("Use -c flag to update values in this column."))
         else:
         else:
             if i == "n":
             if i == "n":
                 coltype = "INTEGER"
                 coltype = "INTEGER"
@@ -277,7 +279,9 @@ def main():
                          " of vector map <{vector}>."
                          " of vector map <{vector}>."
                          ).format(raster=raster, vector=vector)))
                          ).format(raster=raster, vector=vector)))
     except CalledModuleError:
     except CalledModuleError:
-        grass.warning(_("Failed to upload statistics to attribute table of vector map <%s>.") % vector)
+        grass.warning(
+            _("Failed to upload statistics to attribute table of vector map <%s>.") %
+            vector)
         exitcode = 1
         exitcode = 1
 
 
     sys.exit(exitcode)
     sys.exit(exitcode)

+ 25 - 23
scripts/v.report/v.report.py

@@ -47,6 +47,7 @@ import sys
 import os
 import os
 import grass.script as grass
 import grass.script as grass
 
 
+
 def uniq(l):
 def uniq(l):
     result = []
     result = []
     last = None
     last = None
@@ -56,6 +57,7 @@ def uniq(l):
             last = i
             last = i
     return result
     return result
 
 
+
 def main():
 def main():
     mapname = options['map']
     mapname = options['map']
     option = options['option']
     option = options['option']
@@ -75,13 +77,13 @@ def main():
         colnames = ['cat']
         colnames = ['cat']
 
 
     if option == 'coor':
     if option == 'coor':
-        columns = ['dummy1','dummy2','dummy3']
-        extracolnames = ['x','y','z']
+        columns = ['dummy1', 'dummy2', 'dummy3']
+        extracolnames = ['x', 'y', 'z']
     else:
     else:
         columns = ['dummy1']
         columns = ['dummy1']
         extracolnames = [option]
         extracolnames = [option]
 
 
-    if units in ['p','percent']:
+    if units in ['p', 'percent']:
         unitsp = 'meters'
         unitsp = 'meters'
     elif units:
     elif units:
         unitsp = units
         unitsp = units
@@ -90,7 +92,7 @@ def main():
 
 
     # NOTE: we suppress -1 cat and 0 cat
     # NOTE: we suppress -1 cat and 0 cat
     if isConnection:
     if isConnection:
-        p = grass.pipe_command('v.db.select', quiet = True, flags='c', map = mapname, layer = layer)
+        p = grass.pipe_command('v.db.select', quiet=True, flags='c', map=mapname, layer=layer)
         records1 = []
         records1 = []
         for line in p.stdout:
         for line in p.stdout:
             cols = line.rstrip('\r\n').split('|')
             cols = line.rstrip('\r\n').split('|')
@@ -100,23 +102,23 @@ def main():
         p.wait()
         p.wait()
         if p.returncode != 0:
         if p.returncode != 0:
             sys.exit(1)
             sys.exit(1)
-        
+
         records1.sort()
         records1.sort()
 
 
         if len(records1) == 0:
         if len(records1) == 0:
             try:
             try:
-                f = grass.vector_db(map = mapname)[int(layer)]
+                f = grass.vector_db(map=mapname)[int(layer)]
                 grass.fatal(_("There is a table connected to input vector map '%s', but"
                 grass.fatal(_("There is a table connected to input vector map '%s', but"
                               "there are no categories present in the key column '%s'. Consider using"
                               "there are no categories present in the key column '%s'. Consider using"
                               "v.to.db to correct this.") % (mapname, f['key']))
                               "v.to.db to correct this.") % (mapname, f['key']))
             except KeyError:
             except KeyError:
                 pass
                 pass
 
 
-        #fetch the requested attribute sorted by cat:
-        p = grass.pipe_command('v.to.db', flags = 'p',
-                               quiet = True,
-                               map = mapname, option = option, columns = columns,
-                               layer = layer, units = unitsp)
+        # fetch the requested attribute sorted by cat:
+        p = grass.pipe_command('v.to.db', flags='p',
+                               quiet=True,
+                               map=mapname, option=option, columns=columns,
+                               layer=layer, units=unitsp)
         records2 = []
         records2 = []
         for line in p.stdout:
         for line in p.stdout:
             fields = line.rstrip('\r\n').split('|')
             fields = line.rstrip('\r\n').split('|')
@@ -126,7 +128,7 @@ def main():
         p.wait()
         p.wait()
         records2.sort()
         records2.sort()
 
 
-        #make pre-table
+        # make pre-table
         # len(records1) may not be the same as len(records2) because
         # len(records1) may not be the same as len(records2) because
         # v.db.select can return attributes that are not linked to features.
         # v.db.select can return attributes that are not linked to features.
         records3 = []
         records3 = []
@@ -134,7 +136,7 @@ def main():
             records3.append(filter(lambda r1: r1[0] == r2[0], records1)[0] + r2[1:])
             records3.append(filter(lambda r1: r1[0] == r2[0], records1)[0] + r2[1:])
     else:
     else:
         records1 = []
         records1 = []
-        p = grass.pipe_command('v.category', inp = mapname, layer = layer, option = 'print')
+        p = grass.pipe_command('v.category', inp=mapname, layer=layer, option='print')
         for line in p.stdout:
         for line in p.stdout:
             field = int(line.rstrip())
             field = int(line.rstrip())
             if field > 0:
             if field > 0:
@@ -143,10 +145,10 @@ def main():
         records1.sort()
         records1.sort()
         records1 = uniq(records1)
         records1 = uniq(records1)
 
 
-        #make pre-table
-        p = grass.pipe_command('v.to.db', flags = 'p',
-                               map = mapname, option = option, columns = columns,
-                               layer = layer, units = unitsp)
+        # make pre-table
+        p = grass.pipe_command('v.to.db', flags='p',
+                               map=mapname, option=option, columns=columns,
+                               layer=layer, units=unitsp)
         records3 = []
         records3 = []
         for line in p.stdout:
         for line in p.stdout:
             fields = line.split('|')
             fields = line.split('|')
@@ -159,11 +161,11 @@ def main():
     # print table header
     # print table header
     sys.stdout.write('|'.join(colnames + extracolnames) + '\n')
     sys.stdout.write('|'.join(colnames + extracolnames) + '\n')
 
 
-    #make and print the table:
+    # make and print the table:
     numcols = len(colnames) + len(extracolnames)
     numcols = len(colnames) + len(extracolnames)
 
 
     # calculate percents if requested
     # calculate percents if requested
-    if units != '' and units in ['p','percent']:
+    if units != '' and units in ['p', 'percent']:
         # calculate total area value
         # calculate total area value
         areatot = 0
         areatot = 0
         for r in records3:
         for r in records3:
@@ -176,12 +178,12 @@ def main():
     # sort results
     # sort results
     if options['sort']:
     if options['sort']:
         if options['sort'] == 'asc':
         if options['sort'] == 'asc':
-            records3.sort(key = lambda r: r[-1])
+            records3.sort(key=lambda r: r[-1])
         else:
         else:
-            records3.sort(key = lambda r: r[-1], reverse = True)
-    
+            records3.sort(key=lambda r: r[-1], reverse=True)
+
     for r in records3:
     for r in records3:
-        sys.stdout.write('|'.join(map(str,r)) + '\n')
+        sys.stdout.write('|'.join(map(str, r)) + '\n')
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
     options, flags = grass.parser()
     options, flags = grass.parser()

+ 7 - 6
scripts/v.unpack/v.unpack.py

@@ -116,7 +116,8 @@ def main():
     skip_projection_check = False
     skip_projection_check = False
     if not os.path.exists(os.path.join(tmp_dir, 'PROJ_INFO')):
     if not os.path.exists(os.path.join(tmp_dir, 'PROJ_INFO')):
         if os.path.exists(loc_proj):
         if os.path.exists(loc_proj):
-            grass.fatal(_("PROJ_INFO file is missing, unpack vector map in XY (unprojected) location."))
+            grass.fatal(
+                _("PROJ_INFO file is missing, unpack vector map in XY (unprojected) location."))
         skip_projection_check = True  # XY location
         skip_projection_check = True  # XY location
 
 
     if not skip_projection_check:
     if not skip_projection_check:
@@ -124,14 +125,14 @@ def main():
         if not grass.compare_key_value_text_files(filename_a=os.path.join(tmp_dir, 'PROJ_INFO'),
         if not grass.compare_key_value_text_files(filename_a=os.path.join(tmp_dir, 'PROJ_INFO'),
                                                   filename_b=loc_proj, proj=True):
                                                   filename_b=loc_proj, proj=True):
             diff_result_1 = diff_files(os.path.join(tmp_dir, 'PROJ_INFO'),
             diff_result_1 = diff_files(os.path.join(tmp_dir, 'PROJ_INFO'),
-                                             loc_proj)
-    
+                                       loc_proj)
+
         if not grass.compare_key_value_text_files(filename_a=os.path.join(tmp_dir, 'PROJ_UNITS'),
         if not grass.compare_key_value_text_files(filename_a=os.path.join(tmp_dir, 'PROJ_UNITS'),
                                                   filename_b=loc_proj_units,
                                                   filename_b=loc_proj_units,
                                                   units=True):
                                                   units=True):
             diff_result_2 = diff_files(os.path.join(tmp_dir, 'PROJ_UNITS'),
             diff_result_2 = diff_files(os.path.join(tmp_dir, 'PROJ_UNITS'),
-                                             loc_proj_units)
-    
+                                       loc_proj_units)
+
         if diff_result_1 or diff_result_2:
         if diff_result_1 or diff_result_2:
             if flags['o']:
             if flags['o']:
                 grass.warning(_("Projection information does not match. Proceeding..."))
                 grass.warning(_("Projection information does not match. Proceeding..."))
@@ -167,7 +168,7 @@ def main():
         # check if dbf or sqlite directory exists
         # check if dbf or sqlite directory exists
         if dbconn['driver'] == 'dbf' and not os.path.exists(os.path.join(mset_dir, 'dbf')):
         if dbconn['driver'] == 'dbf' and not os.path.exists(os.path.join(mset_dir, 'dbf')):
             os.mkdir(os.path.join(mset_dir, 'dbf'))
             os.mkdir(os.path.join(mset_dir, 'dbf'))
-	elif dbconn['driver'] == 'sqlite' and not os.path.exists(os.path.join(mset_dir, 'sqlite')):
+        elif dbconn['driver'] == 'sqlite' and not os.path.exists(os.path.join(mset_dir, 'sqlite')):
             os.mkdir(os.path.join(mset_dir, 'sqlite'))
             os.mkdir(os.path.join(mset_dir, 'sqlite'))
         # for each old connection
         # for each old connection
         for t in dbnlist:
         for t in dbnlist:

+ 6 - 6
scripts/v.what.strds/testsuite/test_what_strds.py

@@ -21,12 +21,12 @@ class TestWhatStrds(TestCase):
         """Initiate the temporal GIS and set the region
         """Initiate the temporal GIS and set the region
         """
         """
         cls.use_temp_region()
         cls.use_temp_region()
-        cls.runModule("g.region",  s=0,  n=80,  w=0,  e=120,  b=0,  t=50,
-                      res=10,  res3=10)
-        cls.runModule("r.mapcalc", expression="a_1 = 100",  overwrite=True)
-        cls.runModule("r.mapcalc", expression="a_2 = 200",  overwrite=True)
-        cls.runModule("r.mapcalc", expression="a_3 = 300",  overwrite=True)
-        cls.runModule("r.mapcalc", expression="a_4 = 400",  overwrite=True)
+        cls.runModule("g.region", s=0, n=80, w=0, e=120, b=0, t=50,
+                      res=10, res3=10)
+        cls.runModule("r.mapcalc", expression="a_1 = 100", overwrite=True)
+        cls.runModule("r.mapcalc", expression="a_2 = 200", overwrite=True)
+        cls.runModule("r.mapcalc", expression="a_3 = 300", overwrite=True)
+        cls.runModule("r.mapcalc", expression="a_4 = 400", overwrite=True)
 
 
         cls.runModule("v.random", output="points", npoints=3, seed=1,
         cls.runModule("v.random", output="points", npoints=3, seed=1,
                       overwrite=True)
                       overwrite=True)

+ 4 - 3
scripts/v.what.strds/v.what.strds.py

@@ -60,6 +60,7 @@ from grass.exceptions import CalledModuleError
 
 
 
 
 class Sample(object):
 class Sample(object):
+
     def __init__(self, start=None, end=None, raster_names=None,
     def __init__(self, start=None, end=None, raster_names=None,
                  strds_name=None):
                  strds_name=None):
         self.start = start
         self.start = start
@@ -151,9 +152,9 @@ def main():
                               "datasets must be equal\n<%(a)s> of type "
                               "datasets must be equal\n<%(a)s> of type "
                               "%(type_a)s do not match <%(b)s> of type "
                               "%(type_a)s do not match <%(b)s> of type "
                               "%(type_b)s" % {"a": first_strds.get_id(),
                               "%(type_b)s" % {"a": first_strds.get_id(),
-                               "type_a": first_strds.get_temporal_type(),
-                               "b": dataset.get_id(),
-                               "type_b": dataset.get_temporal_type()}))
+                                              "type_a": first_strds.get_temporal_type(),
+                                              "b": dataset.get_id(),
+                                              "type_b": dataset.get_temporal_type()}))
 
 
         mapmatrizes = tgis.sample_stds_by_stds_topology("strds", "strds",
         mapmatrizes = tgis.sample_stds_by_stds_topology("strds", "strds",
                                                         strds_names,
                                                         strds_names,

+ 2 - 2
scripts/wxpyimgview/wxpyimgview.py

@@ -16,7 +16,7 @@
 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 #  GNU General Public License for more details.
 #  GNU General Public License for more details.
 #
 #
-#############################################################################/
+# /
 
 
 #%module
 #%module
 #% description: Views BMP images from the PNG driver.
 #% description: Views BMP images from the PNG driver.
@@ -43,7 +43,7 @@ import grass.script as grass
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
     options, flags = grass.parser()
     options, flags = grass.parser()
-    image   = options['image']
+    image = options['image']
     percent = options['percent']
     percent = options['percent']
     python = os.getenv('GRASS_PYTHON', 'python')
     python = os.getenv('GRASS_PYTHON', 'python')
     gisbase = os.environ['GISBASE']
     gisbase = os.environ['GISBASE']

+ 78 - 75
scripts/wxpyimgview/wxpyimgview_gui.py

@@ -16,7 +16,7 @@
 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 #  GNU General Public License for more details.
 #  GNU General Public License for more details.
 #
 #
-#############################################################################/
+# /
 
 
 #%module
 #%module
 #% description: Views BMP images from the PNG driver.
 #% description: Views BMP images from the PNG driver.
@@ -46,124 +46,127 @@ import wxversion
 wxversion.select('2.8')
 wxversion.select('2.8')
 import wx
 import wx
 
 
+
 class Frame(wx.Frame):
 class Frame(wx.Frame):
     title = "Image Viewer"
     title = "Image Viewer"
 
 
     def __init__(self, app, size):
     def __init__(self, app, size):
-	self.app = app
-	wx.Frame.__init__(self, None, title = Frame.title, size = size)
-	self.Create()
+        self.app = app
+        wx.Frame.__init__(self, None, title=Frame.title, size=size)
+        self.Create()
 
 
     def Create(self):
     def Create(self):
-	self.Bind(wx.EVT_ERASE_BACKGROUND, self.erase)
-	self.Bind(wx.EVT_PAINT, self.redraw)
+        self.Bind(wx.EVT_ERASE_BACKGROUND, self.erase)
+        self.Bind(wx.EVT_PAINT, self.redraw)
 
 
-	self.Bind(wx.EVT_TIMER, self.tick, id = 1)
-	self.timer = wx.Timer(self, 1)
-	self.timer.Start(100, True)
+        self.Bind(wx.EVT_TIMER, self.tick, id=1)
+        self.timer = wx.Timer(self, 1)
+        self.timer.Start(100, True)
 
 
-	# Python doesn't receive signals while wx is waiting for an event
-	self.Bind(wx.EVT_TIMER, self.dummy, id = 2)
-	self.ticker = wx.Timer(self, 2)
-	self.ticker.Start(100, False)
+        # Python doesn't receive signals while wx is waiting for an event
+        self.Bind(wx.EVT_TIMER, self.dummy, id=2)
+        self.ticker = wx.Timer(self, 2)
+        self.ticker.Start(100, False)
 
 
     def erase(self, ev):
     def erase(self, ev):
-	ev.GetDC();
+        ev.GetDC()
 
 
     def draw(self):
     def draw(self):
-	app = self.app
-	size = self.GetSize()
-	x0 = (size.GetWidth()  - app.i_width) / 2
-	y0 = (size.GetHeight() - app.i_height) / 2
-	dc = wx.PaintDC(self)
-	data = app.imgbuf.reshape((app.i_height, app.i_width, 4))
-	data = data[::,::,2::-1]
-	fn = getattr(data, "tobytes", getattr(data, "tostring"))
-	image = wx.ImageFromData(app.i_width, app.i_height, fn())
-	dc.DrawBitmap(wx.BitmapFromImage(image), x0, y0, False)
+        app = self.app
+        size = self.GetSize()
+        x0 = (size.GetWidth() - app.i_width) / 2
+        y0 = (size.GetHeight() - app.i_height) / 2
+        dc = wx.PaintDC(self)
+        data = app.imgbuf.reshape((app.i_height, app.i_width, 4))
+        data = data[::, ::, 2::-1]
+        fn = getattr(data, "tobytes", getattr(data, "tostring"))
+        image = wx.ImageFromData(app.i_width, app.i_height, fn())
+        dc.DrawBitmap(wx.BitmapFromImage(image), x0, y0, False)
 
 
     def redraw(self, ev):
     def redraw(self, ev):
-	if self.app.fraction > 0.001:
-	    t0 = time.time()
-	    self.draw()
-	    t1 = time.time()
+        if self.app.fraction > 0.001:
+            t0 = time.time()
+            self.draw()
+            t1 = time.time()
 
 
-	    last = t1 - t0
-	    delay = last / self.app.fraction
-	    self.timer.Start(int(delay * 1000), True)
-	else:
-	    self.draw()
+            last = t1 - t0
+            delay = last / self.app.fraction
+            self.timer.Start(int(delay * 1000), True)
+        else:
+            self.draw()
 
 
     def tick(self, ev):
     def tick(self, ev):
-	self.Refresh()
+        self.Refresh()
 
 
     def dummy(self, ev):
     def dummy(self, ev):
-	pass
+        pass
+
 
 
 class Application(wx.App):
 class Application(wx.App):
+
     def __init__(self):
     def __init__(self):
-	self.image = sys.argv[1]
-	self.fraction = int(sys.argv[2]) / 100.0
-	self.HEADER_SIZE = 64
-	wx.App.__init__(self)
+        self.image = sys.argv[1]
+        self.fraction = int(sys.argv[2]) / 100.0
+        self.HEADER_SIZE = 64
+        wx.App.__init__(self)
 
 
     def read_bmp_header(self, header):
     def read_bmp_header(self, header):
-	magic, bmfh, bmih = struct.unpack("2s12s40s10x", header)
+        magic, bmfh, bmih = struct.unpack("2s12s40s10x", header)
 
 
-	if magic != 'BM':
-	    raise SyntaxError("Invalid magic number")
+        if magic != 'BM':
+            raise SyntaxError("Invalid magic number")
 
 
-	size, res1, res2, hsize = struct.unpack("<IHHI", bmfh)
+        size, res1, res2, hsize = struct.unpack("<IHHI", bmfh)
 
 
-	if hsize != self.HEADER_SIZE:
-	    raise SyntaxError("Invalid file header size")
+        if hsize != self.HEADER_SIZE:
+            raise SyntaxError("Invalid file header size")
 
 
-	hsize, width, height, planes, bpp, compression, imsize, xppm, yppm, cused, cimp = \
-	       struct.unpack("<IiiHHIIiiII", bmih)
+        hsize, width, height, planes, bpp, compression, imsize, xppm, yppm, cused, cimp = \
+            struct.unpack("<IiiHHIIiiII", bmih)
 
 
-	if hsize != 40:
-	    raise SyntaxError("Invalid info header size")
+        if hsize != 40:
+            raise SyntaxError("Invalid info header size")
 
 
-	self.i_width = width
-	self.i_height = -height
+        self.i_width = width
+        self.i_height = -height
 
 
-	if planes != 1:
-	    raise SyntaxError("Planar data not supported")
-	if bpp != 32:
-	    raise SyntaxError("Only 32-BPP images supported")
-	if compression != 0:
-	    raise SyntaxError("Compression not supported")
-	if imsize != self.i_width * self.i_height * 4:
-	    raise SyntaxError("Invalid image data size")
-	if size != self.HEADER_SIZE + self.i_width * self.i_height * 4:
-	    raise SyntaxError("Invalid image size")
+        if planes != 1:
+            raise SyntaxError("Planar data not supported")
+        if bpp != 32:
+            raise SyntaxError("Only 32-BPP images supported")
+        if compression != 0:
+            raise SyntaxError("Compression not supported")
+        if imsize != self.i_width * self.i_height * 4:
+            raise SyntaxError("Invalid image data size")
+        if size != self.HEADER_SIZE + self.i_width * self.i_height * 4:
+            raise SyntaxError("Invalid image size")
 
 
     def map_file(self):
     def map_file(self):
-	f = open(self.image, 'r')
+        f = open(self.image, 'r')
 
 
-	header = f.read(self.HEADER_SIZE)
-	self.read_bmp_header(header)
+        header = f.read(self.HEADER_SIZE)
+        self.read_bmp_header(header)
 
 
-	self.imgbuf = numpy.memmap(f, mode = 'r', offset = self.HEADER_SIZE)
+        self.imgbuf = numpy.memmap(f, mode='r', offset=self.HEADER_SIZE)
 
 
     def signal_handler(self, sig, frame):
     def signal_handler(self, sig, frame):
-	wx.CallAfter(self.mainwin.Refresh);
+        wx.CallAfter(self.mainwin.Refresh)
 
 
     def set_handler(self):
     def set_handler(self):
-	if 'SIGUSR1' in dir(signal):
-	    signal.signal(signal.SIGUSR1, self.signal_handler)
+        if 'SIGUSR1' in dir(signal):
+            signal.signal(signal.SIGUSR1, self.signal_handler)
 
 
     def OnInit(self):
     def OnInit(self):
-	self.map_file()
+        self.map_file()
 
 
-	size = wx.Size(self.i_width, self.i_height)
-	self.mainwin = Frame(self, size)
-	self.mainwin.Show()
-	self.SetTopWindow(self.mainwin)
+        size = wx.Size(self.i_width, self.i_height)
+        self.mainwin = Frame(self, size)
+        self.mainwin.Show()
+        self.SetTopWindow(self.mainwin)
 
 
-	self.set_handler()
+        self.set_handler()
 
 
-	return True
+        return True
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
     app = Application()
     app = Application()