[GRASS-SVN] r68364 - in grass/trunk: lib/python/temporal scripts/d.correlate scripts/d.frame scripts/d.polar scripts/d.rast.edit scripts/d.rast.leg scripts/d.redraw scripts/db.dropcolumn scripts/db.in.ogr scripts/db.out.ogr scripts/db.test scripts/db.univar scripts/g.extension scripts/g.extension/testsuite scripts/g.extension.all scripts/g.manual scripts/g.search.modules scripts/g.search.modules/testsuite scripts/i.colors.enhance scripts/i.image.mosaic scripts/i.in.spotvgt scripts/i.oif scripts/i.spectral scripts/i.tasscap scripts/m.proj scripts/r.blend scripts/r.buffer.lowmem scripts/r.colors.stddev scripts/r.fillnulls scripts/r.grow scripts/r.import scripts/r.in.aster scripts/r.in.srtm scripts/r.in.wms scripts/r.mask scripts/r.out.xyz scripts/r.pack scripts/r.plane scripts/r.reclass.area scripts/r.shade scripts/r.tileset scripts/r.unpack scripts/r3.in.xyz scripts/v.build.all scripts/v.centroids scripts/v.db.addcolumn scripts/v.db.addtable scripts/v.db.dropcolumn scripts/v.db.droprow s cripts/v.db.droptable scripts/v.db.join scripts/v.db.reconnect.all scripts/v.db.renamecolumn scripts/v.db.univar scripts/v.db.update scripts/v.dissolve scripts/v.import scripts/v.in.e00 scripts/v.in.geonames scripts/v.in.lines scripts/v.in.mapgen scripts/v.in.wfs scripts/v.krige scripts/v.pack scripts/v.rast.stats scripts/v.rast.stats/testsuite scripts/v.report scripts/v.unpack scripts/v.what.strds scripts/v.what.strds/testsuite scripts/wxpyimgview

svn_grass at osgeo.org svn_grass at osgeo.org
Mon May 2 09:11:41 PDT 2016


Author: zarch
Date: 2016-05-02 09:11:41 -0700 (Mon, 02 May 2016)
New Revision: 68364

Modified:
   grass/trunk/lib/python/temporal/__init__.py
   grass/trunk/lib/python/temporal/abstract_dataset.py
   grass/trunk/lib/python/temporal/abstract_map_dataset.py
   grass/trunk/lib/python/temporal/abstract_space_time_dataset.py
   grass/trunk/lib/python/temporal/aggregation.py
   grass/trunk/lib/python/temporal/base.py
   grass/trunk/lib/python/temporal/c_libraries_interface.py
   grass/trunk/lib/python/temporal/core.py
   grass/trunk/lib/python/temporal/datetime_math.py
   grass/trunk/lib/python/temporal/extract.py
   grass/trunk/lib/python/temporal/factory.py
   grass/trunk/lib/python/temporal/gui_support.py
   grass/trunk/lib/python/temporal/list_stds.py
   grass/trunk/lib/python/temporal/mapcalc.py
   grass/trunk/lib/python/temporal/metadata.py
   grass/trunk/lib/python/temporal/open_stds.py
   grass/trunk/lib/python/temporal/register.py
   grass/trunk/lib/python/temporal/sampling.py
   grass/trunk/lib/python/temporal/space_time_datasets.py
   grass/trunk/lib/python/temporal/spatial_extent.py
   grass/trunk/lib/python/temporal/spatial_topology_dataset_connector.py
   grass/trunk/lib/python/temporal/spatio_temporal_relationships.py
   grass/trunk/lib/python/temporal/stds_export.py
   grass/trunk/lib/python/temporal/stds_import.py
   grass/trunk/lib/python/temporal/temporal_algebra.py
   grass/trunk/lib/python/temporal/temporal_extent.py
   grass/trunk/lib/python/temporal/temporal_granularity.py
   grass/trunk/lib/python/temporal/temporal_operator.py
   grass/trunk/lib/python/temporal/temporal_raster3d_algebra.py
   grass/trunk/lib/python/temporal/temporal_raster_algebra.py
   grass/trunk/lib/python/temporal/temporal_raster_base_algebra.py
   grass/trunk/lib/python/temporal/temporal_topology_dataset_connector.py
   grass/trunk/lib/python/temporal/temporal_vector_algebra.py
   grass/trunk/lib/python/temporal/unit_tests.py
   grass/trunk/lib/python/temporal/univar_statistics.py
   grass/trunk/scripts/d.correlate/d.correlate.py
   grass/trunk/scripts/d.frame/d.frame.py
   grass/trunk/scripts/d.polar/d.polar.py
   grass/trunk/scripts/d.rast.edit/d.rast.edit.py
   grass/trunk/scripts/d.rast.leg/d.rast.leg.py
   grass/trunk/scripts/d.redraw/d.redraw.py
   grass/trunk/scripts/db.dropcolumn/db.dropcolumn.py
   grass/trunk/scripts/db.in.ogr/db.in.ogr.py
   grass/trunk/scripts/db.out.ogr/db.out.ogr.py
   grass/trunk/scripts/db.test/db.test.py
   grass/trunk/scripts/db.univar/db.univar.py
   grass/trunk/scripts/g.extension.all/g.extension.all.py
   grass/trunk/scripts/g.extension/g.extension.py
   grass/trunk/scripts/g.extension/testsuite/test_addons_modules.py
   grass/trunk/scripts/g.manual/g.manual.py
   grass/trunk/scripts/g.search.modules/g.search.modules.py
   grass/trunk/scripts/g.search.modules/testsuite/test_g_search_modules.py
   grass/trunk/scripts/i.colors.enhance/i.colors.enhance.py
   grass/trunk/scripts/i.image.mosaic/i.image.mosaic.py
   grass/trunk/scripts/i.in.spotvgt/i.in.spotvgt.py
   grass/trunk/scripts/i.oif/i.oif.py
   grass/trunk/scripts/i.spectral/i.spectral.py
   grass/trunk/scripts/i.tasscap/i.tasscap.py
   grass/trunk/scripts/m.proj/m.proj.py
   grass/trunk/scripts/r.blend/r.blend.py
   grass/trunk/scripts/r.buffer.lowmem/r.buffer.lowmem.py
   grass/trunk/scripts/r.colors.stddev/r.colors.stddev.py
   grass/trunk/scripts/r.fillnulls/r.fillnulls.py
   grass/trunk/scripts/r.grow/r.grow.py
   grass/trunk/scripts/r.import/r.import.py
   grass/trunk/scripts/r.in.aster/r.in.aster.py
   grass/trunk/scripts/r.in.srtm/r.in.srtm.py
   grass/trunk/scripts/r.in.wms/r.in.wms.py
   grass/trunk/scripts/r.in.wms/srs.py
   grass/trunk/scripts/r.in.wms/wms_base.py
   grass/trunk/scripts/r.in.wms/wms_cap_parsers.py
   grass/trunk/scripts/r.in.wms/wms_drv.py
   grass/trunk/scripts/r.in.wms/wms_gdal_drv.py
   grass/trunk/scripts/r.mask/r.mask.py
   grass/trunk/scripts/r.out.xyz/r.out.xyz.py
   grass/trunk/scripts/r.pack/r.pack.py
   grass/trunk/scripts/r.plane/r.plane.py
   grass/trunk/scripts/r.reclass.area/r.reclass.area.py
   grass/trunk/scripts/r.shade/r.shade.py
   grass/trunk/scripts/r.tileset/r.tileset.py
   grass/trunk/scripts/r.unpack/r.unpack.py
   grass/trunk/scripts/r3.in.xyz/r3.in.xyz.py
   grass/trunk/scripts/v.build.all/v.build.all.py
   grass/trunk/scripts/v.centroids/v.centroids.py
   grass/trunk/scripts/v.db.addcolumn/v.db.addcolumn.py
   grass/trunk/scripts/v.db.addtable/v.db.addtable.py
   grass/trunk/scripts/v.db.dropcolumn/v.db.dropcolumn.py
   grass/trunk/scripts/v.db.droprow/v.db.droprow.py
   grass/trunk/scripts/v.db.droptable/v.db.droptable.py
   grass/trunk/scripts/v.db.join/v.db.join.py
   grass/trunk/scripts/v.db.reconnect.all/v.db.reconnect.all.py
   grass/trunk/scripts/v.db.renamecolumn/v.db.renamecolumn.py
   grass/trunk/scripts/v.db.univar/v.db.univar.py
   grass/trunk/scripts/v.db.update/v.db.update.py
   grass/trunk/scripts/v.dissolve/v.dissolve.py
   grass/trunk/scripts/v.import/v.import.py
   grass/trunk/scripts/v.in.e00/v.in.e00.py
   grass/trunk/scripts/v.in.geonames/v.in.geonames.py
   grass/trunk/scripts/v.in.lines/v.in.lines.py
   grass/trunk/scripts/v.in.mapgen/v.in.mapgen.py
   grass/trunk/scripts/v.in.wfs/v.in.wfs.py
   grass/trunk/scripts/v.krige/v.krige.py
   grass/trunk/scripts/v.pack/v.pack.py
   grass/trunk/scripts/v.rast.stats/testsuite/test_v_rast_stats.py
   grass/trunk/scripts/v.rast.stats/v.rast.stats.py
   grass/trunk/scripts/v.report/v.report.py
   grass/trunk/scripts/v.unpack/v.unpack.py
   grass/trunk/scripts/v.what.strds/testsuite/test_what_strds.py
   grass/trunk/scripts/v.what.strds/v.what.strds.py
   grass/trunk/scripts/wxpyimgview/wxpyimgview.py
   grass/trunk/scripts/wxpyimgview/wxpyimgview_gui.py
Log:
temporal: support python3

Fix conflicts during rebasing

Modified: grass/trunk/lib/python/temporal/__init__.py
===================================================================
--- grass/trunk/lib/python/temporal/__init__.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/__init__.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -1,33 +1,35 @@
-from core import *
-from base import *
-from spatial_extent import *
-from metadata import *
-from abstract_dataset import *
-from abstract_map_dataset import *
-from abstract_space_time_dataset import *
-from space_time_datasets import *
-from datetime_math import *
-from open_stds import *
-from factory import *
-from gui_support import *
-from list_stds import *
-from register import *
-from sampling import *
-from aggregation import *
-from extract import *
-from stds_export import *
-from stds_import import *
-from mapcalc import *
-from univar_statistics import *
-from c_libraries_interface import *
-from spatio_temporal_relationships import *
-from spatial_topology_dataset_connector import *
-from temporal_extent import *
-from temporal_topology_dataset_connector import *
-from temporal_granularity import *
-from temporal_algebra import *
-from temporal_vector_algebra import *
-from temporal_raster_base_algebra import *
-from temporal_raster_algebra import *
-from temporal_raster3d_algebra import *
-from temporal_operator import *
+from __future__ import (absolute_import)
+
+from .core import *
+from .base import *
+from .spatial_extent import *
+from .metadata import *
+from .abstract_dataset import *
+from .abstract_map_dataset import *
+from .abstract_space_time_dataset import *
+from .space_time_datasets import *
+from .datetime_math import *
+from .open_stds import *
+from .factory import *
+from .gui_support import *
+from .list_stds import *
+from .register import *
+from .sampling import *
+from .aggregation import *
+from .extract import *
+from .stds_export import *
+from .stds_import import *
+from .mapcalc import *
+from .univar_statistics import *
+from .c_libraries_interface import *
+from .spatio_temporal_relationships import *
+from .spatial_topology_dataset_connector import *
+from .temporal_extent import *
+from .temporal_topology_dataset_connector import *
+from .temporal_granularity import *
+from .temporal_algebra import *
+from .temporal_vector_algebra import *
+from .temporal_raster_base_algebra import *
+from .temporal_raster_algebra import *
+from .temporal_raster3d_algebra import *
+from .temporal_operator import *

Modified: grass/trunk/lib/python/temporal/abstract_dataset.py
===================================================================
--- grass/trunk/lib/python/temporal/abstract_dataset.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/abstract_dataset.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -11,11 +11,11 @@
 :authors: Soeren Gebbert
 """
 from abc import ABCMeta, abstractmethod
-from temporal_extent import *
-from spatial_extent import *
-from metadata import *
-from temporal_topology_dataset_connector import *
-from spatial_topology_dataset_connector import *
+from .temporal_extent import *
+from .spatial_extent import *
+from .metadata import *
+from .temporal_topology_dataset_connector import *
+from .spatial_topology_dataset_connector import *
 
 ###############################################################################
 

Modified: grass/trunk/lib/python/temporal/abstract_map_dataset.py
===================================================================
--- grass/trunk/lib/python/temporal/abstract_map_dataset.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/abstract_map_dataset.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -10,8 +10,9 @@
 
 :authors: Soeren Gebbert
 """
-from abstract_dataset import *
-from datetime_math import *
+from __future__ import print_function
+from .abstract_dataset import *
+from .datetime_math import *
 
 
 class AbstractMapDataset(AbstractDataset):
@@ -199,16 +200,16 @@
         if self.get_type() == "raster":
             #                1         2         3         4         5         6         7
             #      0123456789012345678901234567890123456789012345678901234567890123456789012345678
-            print " +-------------------- Raster Dataset ----------------------------------------+"
+            print(" +-------------------- Raster Dataset ----------------------------------------+")
         if self.get_type() == "raster3d":
             #                1         2         3         4         5         6         7
             #      0123456789012345678901234567890123456789012345678901234567890123456789012345678
-            print " +-------------------- 3D Raster Dataset -------------------------------------+"
+            print(" +-------------------- 3D Raster Dataset -------------------------------------+")
         if self.get_type() == "vector":
             #                1         2         3         4         5         6         7
             #      0123456789012345678901234567890123456789012345678901234567890123456789012345678
-            print " +-------------------- Vector Dataset ----------------------------------------+"
-        print " |                                                                            |"
+            print(" +-------------------- Vector Dataset ----------------------------------------+")
+        print(" |                                                                            |")
         self.base.print_info()
         self.temporal_extent.print_info()
         if self.is_topology_build():
@@ -228,8 +229,8 @@
                 else:
                     string += ",%s" % ds
                 count += 1
-        print " | Registered datasets ........ " + string
-        print " +----------------------------------------------------------------------------+"
+        print(" | Registered datasets ........ " + string)
+        print(" +----------------------------------------------------------------------------+")
 
     def print_shell_info(self):
         """Print information about this object in shell style"""
@@ -247,7 +248,7 @@
                 else:
                     string += ",%s" % ds
                 count += 1
-            print "registered_datasets=" + string
+            print("registered_datasets=" + string)
 
         if self.is_topology_build():
             self.print_topology_shell_info()
@@ -539,25 +540,25 @@
                >>> map      = tgis.RasterDataset(None)
                >>> temp_ext = tgis.RasterRelativeTime(start_time=1, end_time=2, unit="years")
                >>> map.set_temporal_extent(temp_ext)
-               >>> print map.get_temporal_extent_as_tuple()
+               >>> print(map.get_temporal_extent_as_tuple())
                (1, 2)
                >>> map      = tgis.VectorDataset(None)
                >>> temp_ext = tgis.VectorAbsoluteTime(start_time=datetime.datetime(2000, 1, 1),
                ...                                        end_time=datetime.datetime(2001, 1, 1))
                >>> map.set_temporal_extent(temp_ext)
-               >>> print map.get_temporal_extent_as_tuple()
+               >>> print(map.get_temporal_extent_as_tuple())
                (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2001, 1, 1, 0, 0))
 
                >>> map1 = tgis.VectorDataset("A at P")
                >>> check = map1.set_absolute_time(datetime.datetime(2000,5,5), datetime.datetime(2005,6,6))
-               >>> print map1.get_temporal_extent_as_tuple()
+               >>> print(map1.get_temporal_extent_as_tuple())
                (datetime.datetime(2000, 5, 5, 0, 0), datetime.datetime(2005, 6, 6, 0, 0))
                >>> map2 = tgis.RasterDataset("B at P")
                >>> check = map2.set_absolute_time(datetime.datetime(1990,1,1), datetime.datetime(1999,8,1))
-               >>> print map2.get_temporal_extent_as_tuple()
+               >>> print(map2.get_temporal_extent_as_tuple())
                (datetime.datetime(1990, 1, 1, 0, 0), datetime.datetime(1999, 8, 1, 0, 0))
                >>> map2.set_temporal_extent(map1.get_temporal_extent())
-               >>> print map2.get_temporal_extent_as_tuple()
+               >>> print(map2.get_temporal_extent_as_tuple())
                (datetime.datetime(2000, 5, 5, 0, 0), datetime.datetime(2005, 6, 6, 0, 0))
 
         """
@@ -710,7 +711,7 @@
                >>> map      = tgis.RasterDataset(None)
                >>> spat_ext = tgis.SpatialExtent(north=10, south=-10, east=20, west=-20, top=5, bottom=-5)
                >>> map.set_spatial_extent(spat_ext)
-               >>> print map.get_spatial_extent_as_tuple()
+               >>> print(map.get_spatial_extent_as_tuple())
                (10.0, -10.0, 20.0, -20.0, 5.0, -5.0)
 
         """
@@ -729,7 +730,7 @@
                >>> spat_ext = tgis.SpatialExtent(north=10, south=-10, east=20, west=-20, top=5, bottom=-5)
                >>> map.set_spatial_extent(spat_ext)
                >>> map.spatial_buffer(10)
-               >>> print map.get_spatial_extent_as_tuple()
+               >>> print(map.get_spatial_extent_as_tuple())
                (20.0, -20.0, 30.0, -30.0, 15.0, -15.0)
 
         """
@@ -756,7 +757,7 @@
                >>> spat_ext = tgis.SpatialExtent(north=10, south=-10, east=20, west=-20, top=5, bottom=-5)
                >>> map.set_spatial_extent(spat_ext)
                >>> map.spatial_buffer_2d(10)
-               >>> print map.get_spatial_extent_as_tuple()
+               >>> print(map.get_spatial_extent_as_tuple())
                (20.0, -20.0, 30.0, -30.0, 5.0, -5.0)
 
         """

Modified: grass/trunk/lib/python/temporal/abstract_space_time_dataset.py
===================================================================
--- grass/trunk/lib/python/temporal/abstract_space_time_dataset.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/abstract_space_time_dataset.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -10,11 +10,12 @@
 
 :authors: Soeren Gebbert
 """
+from __future__ import print_function
 import sys
 import uuid
-from abstract_dataset import *
-from temporal_granularity import *
-from spatio_temporal_relationships import *
+from .abstract_dataset import *
+from .temporal_granularity import *
+from .spatio_temporal_relationships import *
 
 ###############################################################################
 
@@ -98,21 +99,21 @@
         if self.get_type() == "strds":
             #                1         2         3         4         5         6         7
             #      0123456789012345678901234567890123456789012345678901234567890123456789012345678
-            print " +-------------------- Space Time Raster Dataset -----------------------------+"
+            print(" +-------------------- Space Time Raster Dataset -----------------------------+")
         if self.get_type() == "str3ds":
             #                1         2         3         4         5         6         7
             #      0123456789012345678901234567890123456789012345678901234567890123456789012345678
-            print " +-------------------- Space Time 3D Raster Dataset --------------------------+"
+            print(" +-------------------- Space Time 3D Raster Dataset --------------------------+")
         if self.get_type() == "stvds":
             #                1         2         3         4         5         6         7
             #      0123456789012345678901234567890123456789012345678901234567890123456789012345678
-            print " +-------------------- Space Time Vector Dataset -----------------------------+"
-        print " |                                                                            |"
+            print(" +-------------------- Space Time Vector Dataset -----------------------------+")
+        print(" |                                                                            |")
         self.base.print_info()
         self.temporal_extent.print_info()
         self.spatial_extent.print_info()
         self.metadata.print_info()
-        print " +----------------------------------------------------------------------------+"
+        print(" +----------------------------------------------------------------------------+")
 
     def print_shell_info(self):
         """Print information about this class in shell style"""
@@ -1137,7 +1138,7 @@
                 ...     maps.append(map)
                 >>> grans = tgis.AbstractSpaceTimeDataset.resample_maplist_by_granularity(maps,0,8,1)
                 >>> for map_list in grans:
-                ...    print map_list[0].get_id(), map_list[0].get_temporal_extent_as_tuple()
+                ...    print(map_list[0].get_id(), map_list[0].get_temporal_extent_as_tuple())
                 None (0, 1)
                 None (1, 2)
                 map0 at PERMANENT (2, 3)
@@ -1156,7 +1157,7 @@
                 >>> maps.append(map2)
                 >>> grans = tgis.AbstractSpaceTimeDataset.resample_maplist_by_granularity(maps,0,16,2)
                 >>> for map_list in grans:
-                ...    print map_list[0].get_id(), map_list[0].get_temporal_extent_as_tuple()
+                ...    print(map_list[0].get_id(), map_list[0].get_temporal_extent_as_tuple())
                 None (0, 2)
                 map1 at PERMANENT (2, 4)
                 map1 at PERMANENT (4, 6)
@@ -1175,7 +1176,7 @@
                 >>> maps.append(map2)
                 >>> grans = tgis.AbstractSpaceTimeDataset.resample_maplist_by_granularity(maps,0,16,2)
                 >>> for map_list in grans:
-                ...    print map_list[0].get_id(), map_list[0].get_temporal_extent_as_tuple()
+                ...    print(map_list[0].get_id(), map_list[0].get_temporal_extent_as_tuple())
                 None (0, 2)
                 map1 at PERMANENT (2, 4)
                 None (4, 6)
@@ -1194,7 +1195,7 @@
                 >>> maps.append(map2)
                 >>> grans = tgis.AbstractSpaceTimeDataset.resample_maplist_by_granularity(maps,datetime(2000,1,1),datetime(2001,4,1),"1 month")
                 >>> for map_list in grans:
-                ...    print map_list[0].get_id(), map_list[0].get_temporal_extent_as_tuple()
+                ...    print(map_list[0].get_id(), map_list[0].get_temporal_extent_as_tuple())
                 None (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2000, 2, 1, 0, 0))
                 None (datetime.datetime(2000, 2, 1, 0, 0), datetime.datetime(2000, 3, 1, 0, 0))
                 None (datetime.datetime(2000, 3, 1, 0, 0), datetime.datetime(2000, 4, 1, 0, 0))

Modified: grass/trunk/lib/python/temporal/aggregation.py
===================================================================
--- grass/trunk/lib/python/temporal/aggregation.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/aggregation.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -17,10 +17,10 @@
 :author: Soeren Gebbert
 """
 
-from space_time_datasets import *
-from datetime_math import create_suffix_from_datetime
-from datetime_math import create_time_suffix
-from datetime_math import create_numeric_suffic
+from .space_time_datasets import *
+from .datetime_math import create_suffix_from_datetime
+from .datetime_math import create_time_suffix
+from .datetime_math import create_numeric_suffic
 import grass.script as gscript
 from grass.exceptions import CalledModuleError
 

Modified: grass/trunk/lib/python/temporal/base.py
===================================================================
--- grass/trunk/lib/python/temporal/base.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/base.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -24,9 +24,9 @@
 
 :author: Soeren Gebbert
 """
-
+from __future__ import print_function
 from datetime import datetime
-from core import *
+from .core import *
 
 ###############################################################################
 
@@ -186,7 +186,7 @@
     def print_self(self):
         """Print the content of the internal dictionary to stdout
         """
-        print self.D
+        print(self.D)
 
 ###############################################################################
 
@@ -276,7 +276,7 @@
                         if None a temporary connection will be established
         """
         sql = self.get_delete_statement()
-        #print sql
+        #print(sql)
 
         if dbif:
             dbif.execute(sql,   mapset=self.mapset)
@@ -350,8 +350,8 @@
                         if None a temporary connection will be established
         """
         sql, args = self.get_select_statement()
-        #print sql
-        #print args
+        #print(sql)
+        #print(args)
 
         if dbif:
             if len(args) == 0:
@@ -408,8 +408,8 @@
                         if None a temporary connection will be established
         """
         sql, args = self.get_insert_statement()
-        #print sql
-        #print args
+        #print(sql)
+        #print(args)
 
         if dbif:
             dbif.execute(sql, args, mapset=self.mapset)
@@ -462,8 +462,8 @@
             self.msgr.fatal(_("Missing identifer"))
 
         sql, args = self.get_update_statement(ident)
-        #print sql
-        #print args
+        #print(sql)
+        #print(args)
 
         if dbif:
             dbif.execute(sql, args, mapset=self.mapset)
@@ -513,8 +513,8 @@
             self.msgr.fatal(_("Missing identifer"))
 
         sql, args = self.get_update_all_statement(ident)
-        #print sql
-        #print args
+        #print(sql)
+        #print(args)
 
         if dbif:
             dbif.execute(sql, args, mapset=self.mapset)
@@ -766,26 +766,26 @@
     def print_info(self):
         """Print information about this class in human readable style"""
         #      0123456789012345678901234567890
-        print " +-------------------- Basic information -------------------------------------+"
-        print " | Id: ........................ " + str(self.get_id())
-        print " | Name: ...................... " + str(self.get_name())
-        print " | Mapset: .................... " + str(self.get_mapset())
+        print( " +-------------------- Basic information -------------------------------------+")
+        print( " | Id: ........................ " + str(self.get_id()))
+        print(" | Name: ...................... " + str(self.get_name()))
+        print(" | Mapset: .................... " + str(self.get_mapset()))
         if self.get_layer():
-            print " | Layer:...................... " + str(self.get_layer())
-        print " | Creator: ................... " + str(self.get_creator())
-        print " | Temporal type: ............. " + str(self.get_ttype())
-        print " | Creation time: ............. " + str(self.get_ctime())
+            print(" | Layer:...................... " + str(self.get_layer()))
+        print(" | Creator: ................... " + str(self.get_creator()))
+        print(" | Temporal type: ............. " + str(self.get_ttype()))
+        print(" | Creation time: ............. " + str(self.get_ctime()))
 
     def print_shell_info(self):
         """Print information about this class in shell style"""
-        print "id=" + str(self.get_id())
-        print "name=" + str(self.get_name())
-        print "mapset=" + str(self.get_mapset())
+        print("id=" + str(self.get_id()))
+        print("name=" + str(self.get_name()))
+        print("mapset=" + str(self.get_mapset()))
         if self.get_layer():
-            print "layer=" + str(self.get_layer())
-        print "creator=" + str(self.get_creator())
-        print "temporal_type=" + str(self.get_ttype())
-        print "creation_time=" + str(self.get_ctime())
+            print("layer=" + str(self.get_layer()))
+        print("creator=" + str(self.get_creator()))
+        print("temporal_type=" + str(self.get_ttype()))
+        print("creation_time=" + str(self.get_ctime()))
 
 ###############################################################################
 
@@ -901,7 +901,7 @@
 
            :return: None if not found
         """
-        if self.D.has_key("modification_time"):
+        if "modification_time" in self.D:
             return self.D["modification_time"]
         else:
             return None
@@ -912,15 +912,15 @@
         """Print information about this class in human readable style"""
         DatasetBase.print_info(self)
         #      0123456789012345678901234567890
-        print " | Modification time:.......... " + str(self.get_mtime())
-        print " | Semantic type:.............. " + str(
-            self.get_semantic_type())
+        print(" | Modification time:.......... " + str(self.get_mtime()))
+        print(" | Semantic type:.............. " + str(
+            self.get_semantic_type()))
 
     def print_shell_info(self):
         """Print information about this class in shell style"""
         DatasetBase.print_shell_info(self)
-        print "modification_time=" + str(self.get_mtime())
-        print "semantic_type=" + str(self.get_semantic_type())
+        print("modification_time=" + str(self.get_mtime()))
+        print("semantic_type=" + str(self.get_semantic_type()))
 
 ###############################################################################
 

Modified: grass/trunk/lib/python/temporal/c_libraries_interface.py
===================================================================
--- grass/trunk/lib/python/temporal/c_libraries_interface.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/c_libraries_interface.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -18,7 +18,7 @@
 from multiprocessing import Process, Lock, Pipe
 import logging
 from ctypes import *
-from core import *
+from .core import *
 import grass.lib.gis as libgis
 import grass.lib.raster as libraster
 import grass.lib.vector as libvector
@@ -59,7 +59,7 @@
 
 
 def _read_map_full_info(lock, conn, data):
-    """Read full map specific metadata from the spatial database using 
+    """Read full map specific metadata from the spatial database using
        PyGRASS functions.
 
        :param lock: A multiprocessing.Lock instance
@@ -85,21 +85,21 @@
 
 def _read_raster_full_info(name, mapset):
     """Read raster info, history and cats using PyGRASS RasterRow
-       and return a dictionary. Colors should be supported in the 
+       and return a dictionary. Colors should be supported in the
        future.
     """
-    
+
     info = {}
     r = RasterRow(name=name, mapset=mapset)
     if r.exist() is True:
         r.open("r")
-        
+
         for item in r.info:
             info[item[0]] = item[1]
 
         for item in r.hist:
             info[item[0]] = item[1]
-        
+
         info["full_name"] = r.name_mapset()
         info["mtype"] = r.mtype
         if r.cats:
@@ -150,14 +150,14 @@
         info["title"] = v.title
         info["thresh"] = v.thresh
         info["zone"] = v.zone
-        vtypes = ['areas', 'dblinks', 'faces', 'holes', 'islands', 
-                  'kernels', 'lines', 'nodes', 'points', 'updated_lines', 
+        vtypes = ['areas', 'dblinks', 'faces', 'holes', 'islands',
+                  'kernels', 'lines', 'nodes', 'points', 'updated_lines',
                   'updated_nodes', 'volumes']
         for vtype in vtypes:
             info[vtype] = v.number_of(vtype)
-            
+
         info.update(v.num_primitives())
-        
+
         if v.table is not None:
             info["columns"] = v.table.columns
 
@@ -293,15 +293,15 @@
         while mapsets[count]:
             char_list = ""
             mapset = mapsets[count]
-            
+
             permission = libgis.G_mapset_permissions(mapset)
             in_search_path = libgis.G_is_mapset_in_search_path(mapset)
-            
+
             c = 0
             while mapset[c] != "\x00":
                 char_list += mapset[c]
                 c += 1
-            
+
             if permission >= 0 and in_search_path == 1:
                 mapset_list.append(char_list)
 
@@ -1172,10 +1172,10 @@
         self.client_conn.send([RPCDefs.READ_MAP_INFO, RPCDefs.TYPE_RASTER,
                                name, mapset, None])
         return self.safe_receive("read_raster_info")
-        
+
     def read_raster_full_info(self, name, mapset):
         """Read raster info, history and cats using PyGRASS RasterRow
-           and return a dictionary. Colors should be supported in the 
+           and return a dictionary. Colors should be supported in the
            future.
 
            :param name: The name of the map
@@ -1184,7 +1184,7 @@
                      or None in case of an error
         """
         self.check_server()
-        self.client_conn.send([RPCDefs.READ_MAP_FULL_INFO, 
+        self.client_conn.send([RPCDefs.READ_MAP_FULL_INFO,
                                RPCDefs.TYPE_RASTER,
                                name, mapset, None])
         return self.safe_receive("read_raster_full_info")
@@ -1379,7 +1379,7 @@
 
     def read_vector_full_info(self, name, mapset):
         """Read vector info using PyGRASS VectorTopo
-           and return a dictionary. 
+           and return a dictionary.
 
            :param name: The name of the map
            :param mapset: The mapset of the map
@@ -1387,7 +1387,7 @@
                      or None in case of an error
         """
         self.check_server()
-        self.client_conn.send([RPCDefs.READ_MAP_FULL_INFO, 
+        self.client_conn.send([RPCDefs.READ_MAP_FULL_INFO,
                                RPCDefs.TYPE_VECTOR,
                                name, mapset, None])
         return self.safe_receive("read_vector_full_info")

Modified: grass/trunk/lib/python/temporal/core.py
===================================================================
--- grass/trunk/lib/python/temporal/core.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/core.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -34,9 +34,15 @@
 import gettext
 gettext.install('grasslibs', os.path.join(os.getenv("GISBASE"), 'locale'))
 
+try:
+    from builtins import long
+except ImportError:
+    # python3
+    long = int
+
 import grass.script as gscript
 from datetime import datetime
-from c_libraries_interface import *
+from .c_libraries_interface import *
 from grass.pygrass import messages
 # Import all supported database backends
 # Ignore import errors since they are checked later
@@ -61,16 +67,20 @@
     do_profiling = os.getenv("GRASS_TGIS_PROFILE")
 
     if do_profiling is "True" or do_profiling is "1":
-        import cProfile, pstats, StringIO
+        import cProfile, pstats
+        try:
+            import StringIO as io
+        except ImportError:
+            import io
         pr = cProfile.Profile()
         pr.enable()
         func()
         pr.disable()
-        s = StringIO.StringIO()
+        s = io.StringIO()
         sortby = 'cumulative'
         ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
         ps.print_stats()
-        print s.getvalue()
+        print(s.getvalue())
     else:
         func()
 
@@ -560,13 +570,13 @@
     database_string = ciface.get_database_name()
 
     # Set the mapset check and the timestamp write
-    if grassenv.has_key("TGIS_DISABLE_MAPSET_CHECK"):
+    if "TGIS_DISABLE_MAPSET_CHECK" in grassenv:
         if grassenv["TGIS_DISABLE_MAPSET_CHECK"] == "True" or \
            grassenv["TGIS_DISABLE_MAPSET_CHECK"] == "1":
             enable_mapset_check = False
             msgr.warning("TGIS_DISABLE_MAPSET_CHECK is True")
 
-    if grassenv.has_key("TGIS_DISABLE_TIMESTAMP_WRITE"):
+    if "TGIS_DISABLE_TIMESTAMP_WRITE" in grassenv:
         if grassenv["TGIS_DISABLE_TIMESTAMP_WRITE"] == "True" or \
            grassenv["TGIS_DISABLE_TIMESTAMP_WRITE"] == "1":
             enable_timestamp_write = False
@@ -1161,9 +1171,9 @@
                 if self.connected:
                     try:
                         return self.cursor.mogrify(sql, args)
-                    except:
-                        print sql, args
-                        raise
+                    except Exception as exc:
+                        print(sql, args)
+                        raise exc
                 else:
                     self.connect()
                     statement = self.cursor.mogrify(sql, args)

Modified: grass/trunk/lib/python/temporal/datetime_math.py
===================================================================
--- grass/trunk/lib/python/temporal/datetime_math.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/datetime_math.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -9,7 +9,7 @@
 :authors: Soeren Gebbert
 """
 from datetime import datetime, timedelta
-from core import *
+from .core import *
 import copy
 
 try:
@@ -863,9 +863,9 @@
 
 def create_time_suffix(mapp, end=False):
     """Create a datetime string based on a map datetime object
-    
+
        :param mapp: a temporal map dataset
-       :param end: True if you want add also end time to the suffix    
+       :param end: True if you want add also end time to the suffix
     """
     start = mapp.temporal_extent.get_start_time()
     sstring = start.isoformat().replace(':', '_').replace('-', '_')

Modified: grass/trunk/lib/python/temporal/extract.py
===================================================================
--- grass/trunk/lib/python/temporal/extract.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/extract.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -10,11 +10,11 @@
 """
 
 from grass.script.utils import get_num_suffix
-from space_time_datasets import *
-from open_stds import *
-from datetime_math import create_suffix_from_datetime
-from datetime_math import create_time_suffix
-from datetime_math import create_numeric_suffic
+from .space_time_datasets import *
+from .open_stds import *
+from .datetime_math import create_suffix_from_datetime
+from .datetime_math import create_time_suffix
+from .datetime_math import create_numeric_suffic
 from multiprocessing import Process
 import grass.script as gscript
 from grass.exceptions import CalledModuleError
@@ -183,7 +183,7 @@
         msgr.percent(0, num_rows, 1)
 
         temporal_type, semantic_type, title, description = sp.get_initial_values()
-        new_sp = open_new_stds(output, type, sp.get_temporal_type(), title, 
+        new_sp = open_new_stds(output, type, sp.get_temporal_type(), title,
                                description, semantic_type, dbif,
                                gscript.overwrite())
 

Modified: grass/trunk/lib/python/temporal/factory.py
===================================================================
--- grass/trunk/lib/python/temporal/factory.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/factory.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -18,7 +18,7 @@
 :authors: Soeren Gebbert
 """
 
-from space_time_datasets import *
+from .space_time_datasets import *
 
 ###############################################################################
 

Modified: grass/trunk/lib/python/temporal/gui_support.py
===================================================================
--- grass/trunk/lib/python/temporal/gui_support.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/gui_support.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -10,8 +10,8 @@
 :authors: Soeren Gebbert
 """
 
-from space_time_datasets import *
-from factory import *
+from .space_time_datasets import *
+from .factory import *
 import grass.script as gscript
 
 ###############################################################################

Modified: grass/trunk/lib/python/temporal/list_stds.py
===================================================================
--- grass/trunk/lib/python/temporal/list_stds.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/list_stds.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -17,11 +17,11 @@
 
 :authors: Soeren Gebbert
 """
+from __future__ import print_function
+from .space_time_datasets import *
+from .factory import *
+from .open_stds import *
 
-from space_time_datasets import *
-from factory import *
-from open_stds import *
-
 ###############################################################################
 
 
@@ -58,13 +58,13 @@
             >>> rows =  stds_list[mapset]
             >>> for row in rows:
             ...     if row["name"] == name:
-            ...         print True
+            ...         print(True)
             True
             >>> stds_list = tgis.get_dataset_list("strds", "absolute", columns="name,mapset", where="mapset = '%s'"%(mapset))
             >>> rows =  stds_list[mapset]
             >>> for row in rows:
             ...     if row["name"] == name and row["mapset"] == mapset:
-            ...         print True
+            ...         print(True)
             True
             >>> check = sp.delete()
 
@@ -192,7 +192,7 @@
             if outpath:
                 outfile.write('{st}\n'.format(st=string))
             else:
-                print string
+                print(string)
 
         if maps and len(maps) > 0:
 
@@ -240,7 +240,7 @@
                 if outpath:
                     outfile.write('{st}\n'.format(st=string))
                 else:
-                    print string
+                    print(string)
 
     else:
         # In comma separated mode only map ids are needed
@@ -262,7 +262,7 @@
                 if outpath:
                     outfile.write('{st}\n'.format(st=string))
                 else:
-                    print string
+                    print(string)
 
             elif method == "cols":
                 # Print the column names if requested
@@ -281,7 +281,7 @@
                     if outpath:
                         outfile.write('{st}\n'.format(st=output))
                     else:
-                        print output
+                        print(output)
 
                 for row in rows:
                     output = ""
@@ -295,7 +295,7 @@
                     if outpath:
                         outfile.write('{st}\n'.format(st=output))
                     else:
-                        print output
+                        print(output)
     if outpath:
         outfile.close()
     if connected:

Modified: grass/trunk/lib/python/temporal/mapcalc.py
===================================================================
--- grass/trunk/lib/python/temporal/mapcalc.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/mapcalc.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -9,8 +9,8 @@
 :authors: Soeren Gebbert
 """
 
-from space_time_datasets import *
-from open_stds import *
+from .space_time_datasets import *
+from .open_stds import *
 from multiprocessing import Process
 import grass.script as gscript
 from grass.exceptions import CalledModuleError

Modified: grass/trunk/lib/python/temporal/metadata.py
===================================================================
--- grass/trunk/lib/python/temporal/metadata.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/metadata.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -21,7 +21,8 @@
 
 :authors: Soeren Gebbert
 """
-from base import *
+from __future__ import print_function
+from .base import *
 
 ###############################################################################
 
@@ -234,26 +235,26 @@
     def print_info(self):
         """Print information about this class in human readable style"""
         #      0123456789012345678901234567890
-        print " | Datatype:................... " + str(self.get_datatype())
-        print " | Number of columns:.......... " + str(self.get_cols())
-        print " | Number of rows:............. " + str(self.get_rows())
-        print " | Number of cells:............ " + str(
-            self.get_number_of_cells())
-        print " | North-South resolution:..... " + str(self.get_nsres())
-        print " | East-west resolution:....... " + str(self.get_ewres())
-        print " | Minimum value:.............. " + str(self.get_min())
-        print " | Maximum value:.............. " + str(self.get_max())
+        print(" | Datatype:................... " + str(self.get_datatype()))
+        print(" | Number of columns:.......... " + str(self.get_cols()))
+        print(" | Number of rows:............. " + str(self.get_rows()))
+        print(" | Number of cells:............ " + str(
+            self.get_number_of_cells()))
+        print(" | North-South resolution:..... " + str(self.get_nsres()))
+        print(" | East-west resolution:....... " + str(self.get_ewres()))
+        print(" | Minimum value:.............. " + str(self.get_min()))
+        print(" | Maximum value:.............. " + str(self.get_max()))
 
     def print_shell_info(self):
         """Print information about this class in shell style"""
-        print "datatype=" + str(self.get_datatype())
-        print "cols=" + str(self.get_cols())
-        print "rows=" + str(self.get_rows())
-        print "number_of_cells=" + str(self.get_number_of_cells())
-        print "nsres=" + str(self.get_nsres())
-        print "ewres=" + str(self.get_ewres())
-        print "min=" + str(self.get_min())
-        print "max=" + str(self.get_max())
+        print("datatype=" + str(self.get_datatype()))
+        print("cols=" + str(self.get_cols()))
+        print("rows=" + str(self.get_rows()))
+        print("number_of_cells=" + str(self.get_number_of_cells()))
+        print("nsres=" + str(self.get_nsres()))
+        print("ewres=" + str(self.get_ewres()))
+        print("min=" + str(self.get_min()))
+        print("max=" + str(self.get_max()))
 
 ###############################################################################
 
@@ -323,7 +324,7 @@
 
     def print_info(self):
         """Print information about this class in human readable style"""
-        print " +-------------------- Metadata information ----------------------------------+"
+        print(" +-------------------- Metadata information ----------------------------------+")
         #      0123456789012345678901234567890
         RasterMetadataBase.print_info(self)
 
@@ -445,18 +446,18 @@
 
     def print_info(self):
         """Print information about this class in human readable style"""
-        print " +-------------------- Metadata information ----------------------------------+"
+        print(" +-------------------- Metadata information ----------------------------------+")
         #      0123456789012345678901234567890
         RasterMetadataBase.print_info(self)
         #      0123456789012345678901234567890
-        print " | Number of depths:........... " + str(self.get_depths())
-        print " | Top-Bottom resolution:...... " + str(self.get_tbres())
+        print(" | Number of depths:........... " + str(self.get_depths()))
+        print(" | Top-Bottom resolution:...... " + str(self.get_tbres()))
 
     def print_shell_info(self):
         """Print information about this class in shell style"""
         RasterMetadataBase.print_shell_info(self)
-        print "depths=" + str(self.get_depths())
-        print "tbres=" + str(self.get_tbres())
+        print("depths=" + str(self.get_depths()))
+        print("tbres=" + str(self.get_tbres()))
 
 ###############################################################################
 
@@ -763,36 +764,36 @@
     def print_info(self):
         """Print information about this class in human readable style"""
         #      0123456789012345678901234567890
-        print " +-------------------- Metadata information ----------------------------------+"
-        print " | Is map 3d .................. " + str(self.get_3d_info())
-        print " | Number of points ........... " + str(self.get_number_of_points())
-        print " | Number of lines ............ " + str(self.get_number_of_lines())
-        print " | Number of boundaries ....... " + str(self.get_number_of_boundaries())
-        print " | Number of centroids ........ " + str(self.get_number_of_centroids())
-        print " | Number of faces ............ " + str(self.get_number_of_faces())
-        print " | Number of kernels .......... " + str(self.get_number_of_kernels())
-        print " | Number of primitives ....... " + str(self.get_number_of_primitives())
-        print " | Number of nodes ............ " + str(self.get_number_of_nodes())
-        print " | Number of areas ............ " + str(self.get_number_of_areas())
-        print " | Number of islands .......... " + str(self.get_number_of_islands())
-        print " | Number of holes ............ " + str(self.get_number_of_holes())
-        print " | Number of volumes .......... " + str(self.get_number_of_volumes())
+        print(" +-------------------- Metadata information ----------------------------------+")
+        print(" | Is map 3d .................. " + str(self.get_3d_info()))
+        print(" | Number of points ........... " + str(self.get_number_of_points()))
+        print(" | Number of lines ............ " + str(self.get_number_of_lines()))
+        print(" | Number of boundaries ....... " + str(self.get_number_of_boundaries()))
+        print(" | Number of centroids ........ " + str(self.get_number_of_centroids()))
+        print(" | Number of faces ............ " + str(self.get_number_of_faces()))
+        print(" | Number of kernels .......... " + str(self.get_number_of_kernels()))
+        print(" | Number of primitives ....... " + str(self.get_number_of_primitives()))
+        print(" | Number of nodes ............ " + str(self.get_number_of_nodes()))
+        print(" | Number of areas ............ " + str(self.get_number_of_areas()))
+        print(" | Number of islands .......... " + str(self.get_number_of_islands()))
+        print(" | Number of holes ............ " + str(self.get_number_of_holes()))
+        print(" | Number of volumes .......... " + str(self.get_number_of_volumes()))
 
     def print_shell_info(self):
         """Print information about this class in shell style"""
-        print "is_3d=" + str(self.get_3d_info())
-        print "points=" + str(self.get_number_of_points())
-        print "lines=" + str(self.get_number_of_lines())
-        print "boundaries=" + str(self.get_number_of_boundaries())
-        print "centroids=" + str(self.get_number_of_centroids())
-        print "faces=" + str(self.get_number_of_faces())
-        print "kernels=" + str(self.get_number_of_kernels())
-        print "primitives=" + str(self.get_number_of_primitives())
-        print "nodes=" + str(self.get_number_of_nodes())
-        print "areas=" + str(self.get_number_of_areas())
-        print "islands=" + str(self.get_number_of_islands())
-        print "holes=" + str(self.get_number_of_holes())
-        print "volumes=" + str(self.get_number_of_volumes())
+        print("is_3d=" + str(self.get_3d_info()))
+        print("points=" + str(self.get_number_of_points()))
+        print("lines=" + str(self.get_number_of_lines()))
+        print("boundaries=" + str(self.get_number_of_boundaries()))
+        print("centroids=" + str(self.get_number_of_centroids()))
+        print("faces=" + str(self.get_number_of_faces()))
+        print("kernels=" + str(self.get_number_of_kernels()))
+        print("primitives=" + str(self.get_number_of_primitives()))
+        print("nodes=" + str(self.get_number_of_nodes()))
+        print("areas=" + str(self.get_number_of_areas()))
+        print("islands=" + str(self.get_number_of_islands()))
+        print("holes=" + str(self.get_number_of_holes()))
+        print("volumes=" + str(self.get_number_of_volumes()))
 
 ###############################################################################
 
@@ -908,29 +909,29 @@
     def print_info(self):
         """Print information about this class in human readable style"""
         #      0123456789012345678901234567890
-        print " | Number of registered maps:.. " + str(
-            self.get_number_of_maps())
-        print " |"
-        print " | Title:"
-        print " | " + str(self.get_title())
-        print " | Description:"
-        print " | " + str(self.get_description())
-        print " | Command history:"
+        print(" | Number of registered maps:.. " + str(
+            self.get_number_of_maps()))
+        print(" |")
+        print(" | Title:")
+        print(" | " + str(self.get_title()))
+        print(" | Description:")
+        print(" | " + str(self.get_description()))
+        print(" | Command history:")
         command = self.get_command()
         if command:
             for token in command.split("\n"):
-                print " | " + str(token)
+                print(" | " + str(token))
 
     def print_history(self):
         """Print history information about this class in human readable
             shell style
         """
         #      0123456789012345678901234567890
-        print "# Title:"
-        print "# " + str(self.get_title())
-        print "# Description:"
-        print "# " + str(self.get_description())
-        print "# Command history:"
+        print("# Title:")
+        print("# " + str(self.get_title()))
+        print("# Description:")
+        print("# " + str(self.get_description()))
+        print("# Command history:")
         command = self.get_command()
 
         if command:
@@ -946,15 +947,15 @@
                 count += 1
                 if len(token) > 1:
                     if token[0] == "#":
-                        print token
+                        print(token)
                     elif count < len(print_list):
-                        print token + " \\"
+                        print(token + " \\")
                     else:
-                        print token
+                        print(token)
 
     def print_shell_info(self):
         """Print information about this class in shell style"""
-        print "number_of_maps=" + str(self.get_number_of_maps())
+        print("number_of_maps=" + str(self.get_number_of_maps()))
 
 ###############################################################################
 
@@ -1142,29 +1143,29 @@
     def print_info(self):
         """Print information about this class in human readable style"""
         #      0123456789012345678901234567890
-        print " | North-South resolution min:. " + str(self.get_nsres_min())
-        print " | North-South resolution max:. " + str(self.get_nsres_max())
-        print " | East-west resolution min:... " + str(self.get_ewres_min())
-        print " | East-west resolution max:... " + str(self.get_ewres_max())
-        print " | Minimum value min:.......... " + str(self.get_min_min())
-        print " | Minimum value max:.......... " + str(self.get_min_max())
-        print " | Maximum value min:.......... " + str(self.get_max_min())
-        print " | Maximum value max:.......... " + str(self.get_max_max())
-        print " | Aggregation type:........... " + str(self.get_aggregation_type())
+        print(" | North-South resolution min:. " + str(self.get_nsres_min()))
+        print(" | North-South resolution max:. " + str(self.get_nsres_max()))
+        print(" | East-west resolution min:... " + str(self.get_ewres_min()))
+        print(" | East-west resolution max:... " + str(self.get_ewres_max()))
+        print(" | Minimum value min:.......... " + str(self.get_min_min()))
+        print(" | Minimum value max:.......... " + str(self.get_min_max()))
+        print(" | Maximum value min:.......... " + str(self.get_max_min()))
+        print(" | Maximum value max:.......... " + str(self.get_max_max()))
+        print(" | Aggregation type:........... " + str(self.get_aggregation_type()))
         STDSMetadataBase.print_info(self)
 
     def print_shell_info(self):
         """Print information about this class in shell style"""
-        print "aggregation_type=" + str(self.get_aggregation_type())
+        print("aggregation_type=" + str(self.get_aggregation_type()))
         STDSMetadataBase.print_shell_info(self)
-        print "nsres_min=" + str(self.get_nsres_min())
-        print "nsres_max=" + str(self.get_nsres_max())
-        print "ewres_min=" + str(self.get_ewres_min())
-        print "ewres_max=" + str(self.get_ewres_max())
-        print "min_min=" + str(self.get_min_min())
-        print "min_max=" + str(self.get_min_max())
-        print "max_min=" + str(self.get_max_min())
-        print "max_max=" + str(self.get_max_max())
+        print("nsres_min=" + str(self.get_nsres_min()))
+        print("nsres_max=" + str(self.get_nsres_max()))
+        print("ewres_min=" + str(self.get_ewres_min()))
+        print("ewres_max=" + str(self.get_ewres_max()))
+        print("min_min=" + str(self.get_min_min()))
+        print("min_max=" + str(self.get_min_max()))
+        print("max_min=" + str(self.get_max_min()))
+        print("max_max=" + str(self.get_max_max()))
 
 
 ###############################################################################
@@ -1261,16 +1262,16 @@
 
     def print_info(self):
         """Print information about this class in human readable style"""
-        print " +-------------------- Metadata information ----------------------------------+"
+        print(" +-------------------- Metadata information ----------------------------------+")
         #      0123456789012345678901234567890
-        print " | Raster register table:...... " + str(
-            self.get_raster_register())
+        print(" | Raster register table:...... " + str(
+            self.get_raster_register()))
         STDSRasterMetadataBase.print_info(self)
 
     def print_shell_info(self):
         """Print information about this class in shell style"""
         STDSRasterMetadataBase.print_shell_info(self)
-        print "raster_register=" + str(self.get_raster_register())
+        print("raster_register=" + str(self.get_raster_register()))
 
 ###############################################################################
 
@@ -1397,21 +1398,21 @@
 
     def print_info(self):
         """Print information about this class in human readable style"""
-        print " +-------------------- Metadata information ----------------------------------+"
+        print(" +-------------------- Metadata information ----------------------------------+")
         #      0123456789012345678901234567890
         #      0123456789012345678901234567890
-        print " | 3D raster register table:... " + str(
-            self.get_raster3d_register())
-        print " | Top-bottom resolution min:.. " + str(self.get_ewres_min())
-        print " | Top-bottom resolution max:.. " + str(self.get_ewres_max())
+        print(" | 3D raster register table:... " + str(
+            self.get_raster3d_register()))
+        print(" | Top-bottom resolution min:.. " + str(self.get_ewres_min()))
+        print(" | Top-bottom resolution max:.. " + str(self.get_ewres_max()))
         STDSRasterMetadataBase.print_info(self)
 
     def print_shell_info(self):
         """Print information about this class in shell style"""
         STDSRasterMetadataBase.print_shell_info(self)
-        print "tbres_min=" + str(self.get_tbres_min())
-        print "tbres_max=" + str(self.get_tbres_max())
-        print "raster3d_register=" + str(self.get_raster3d_register())
+        print("tbres_min=" + str(self.get_tbres_min()))
+        print("tbres_max=" + str(self.get_tbres_max()))
+        print("raster3d_register=" + str(self.get_raster3d_register()))
 
 ###############################################################################
 
@@ -1662,40 +1663,40 @@
 
     def print_info(self):
         """Print information about this class in human readable style"""
-        print " +-------------------- Metadata information ----------------------------------+"
+        print(" +-------------------- Metadata information ----------------------------------+")
         #      0123456789012345678901234567890
-        print " | Vector register table:...... " + str(
-            self.get_vector_register())
-        print " | Number of points ........... " + str(self.number_of_points)
-        print " | Number of lines ............ " + str(self.number_of_lines)
-        print " | Number of boundaries ....... " + str(self.number_of_boundaries)
-        print " | Number of centroids ........ " + str(self.number_of_centroids)
-        print " | Number of faces ............ " + str(self.number_of_faces)
-        print " | Number of kernels .......... " + str(self.number_of_kernels)
-        print " | Number of primitives ....... " + str(self.number_of_primitives)
-        print " | Number of nodes ............ " + str(self.number_of_nodes)
-        print " | Number of areas ............ " + str(self.number_of_areas)
-        print " | Number of islands .......... " + str(self.number_of_islands)
-        print " | Number of holes ............ " + str(self.number_of_holes)
-        print " | Number of volumes .......... " + str(self.number_of_volumes)
+        print(" | Vector register table:...... " + str(
+            self.get_vector_register()))
+        print(" | Number of points ........... " + str(self.number_of_points))
+        print(" | Number of lines ............ " + str(self.number_of_lines))
+        print(" | Number of boundaries ....... " + str(self.number_of_boundaries))
+        print(" | Number of centroids ........ " + str(self.number_of_centroids))
+        print(" | Number of faces ............ " + str(self.number_of_faces))
+        print(" | Number of kernels .......... " + str(self.number_of_kernels))
+        print(" | Number of primitives ....... " + str(self.number_of_primitives))
+        print(" | Number of nodes ............ " + str(self.number_of_nodes))
+        print(" | Number of areas ............ " + str(self.number_of_areas))
+        print(" | Number of islands .......... " + str(self.number_of_islands))
+        print(" | Number of holes ............ " + str(self.number_of_holes))
+        print(" | Number of volumes .......... " + str(self.number_of_volumes))
         STDSMetadataBase.print_info(self)
 
     def print_shell_info(self):
         """Print information about this class in shell style"""
         STDSMetadataBase.print_shell_info(self)
-        print "vector_register=" + str(self.get_vector_register())
-        print "points=" + str(self.get_number_of_points())
-        print "lines=" + str(self.get_number_of_lines())
-        print "boundaries=" + str(self.get_number_of_boundaries())
-        print "centroids=" + str(self.get_number_of_centroids())
-        print "faces=" + str(self.get_number_of_faces())
-        print "kernels=" + str(self.get_number_of_kernels())
-        print "primitives=" + str(self.get_number_of_primitives())
-        print "nodes=" + str(self.get_number_of_nodes())
-        print "areas=" + str(self.get_number_of_areas())
-        print "islands=" + str(self.get_number_of_islands())
-        print "holes=" + str(self.get_number_of_holes())
-        print "volumes=" + str(self.get_number_of_volumes())
+        print("vector_register=" + str(self.get_vector_register()))
+        print("points=" + str(self.get_number_of_points()))
+        print("lines=" + str(self.get_number_of_lines()))
+        print("boundaries=" + str(self.get_number_of_boundaries()))
+        print("centroids=" + str(self.get_number_of_centroids()))
+        print("faces=" + str(self.get_number_of_faces()))
+        print("kernels=" + str(self.get_number_of_kernels()))
+        print("primitives=" + str(self.get_number_of_primitives()))
+        print("nodes=" + str(self.get_number_of_nodes()))
+        print("areas=" + str(self.get_number_of_areas()))
+        print("islands=" + str(self.get_number_of_islands()))
+        print("holes=" + str(self.get_number_of_holes()))
+        print("volumes=" + str(self.get_number_of_volumes()))
 
 ###############################################################################
 

Modified: grass/trunk/lib/python/temporal/open_stds.py
===================================================================
--- grass/trunk/lib/python/temporal/open_stds.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/open_stds.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -18,7 +18,7 @@
 :authors: Soeren Gebbert
 """
 
-from factory import *
+from .factory import *
 
 ###############################################################################
 
@@ -37,7 +37,7 @@
        :param type: The type of the space time dataset (strd, str3ds, stvds,
                     raster, vector, raster3d)
        :param dbif: The optional database interface to be used
-       
+
        :return: New stds object
 
     """

Modified: grass/trunk/lib/python/temporal/register.py
===================================================================
--- grass/trunk/lib/python/temporal/register.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/register.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -17,7 +17,7 @@
 :authors: Soeren Gebbert
 """
 
-from open_stds import *
+from .open_stds import *
 import grass.script as gscript
 
 ###############################################################################

Modified: grass/trunk/lib/python/temporal/sampling.py
===================================================================
--- grass/trunk/lib/python/temporal/sampling.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/sampling.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -16,10 +16,10 @@
 
 :authors: Soeren Gebbert
 """
+from __future__ import print_function
+from .factory import *
 
-from factory import *
 
-
 def sample_stds_by_stds_topology(intype, sampletype, inputs, sampler, header,
                                  separator, method, spatial=False,
                                  print_only=True):
@@ -122,7 +122,7 @@
             string += "%s%s" % ("end_time", separator)
             string += "%s%s" % ("interval_length", separator)
             string += "%s" % ("distance_from_begin")
-            print string
+            print(string)
 
         first_time, dummy = mapmatrizes[0][0]["granule"].get_temporal_extent_as_tuple()
 
@@ -163,7 +163,7 @@
             string += "%s%s" % (end, separator)
             string += "%s%s" % (delta, separator)
             string += "%s" % (delta_first)
-            print string
+            print(string)
 
     dbif.close()
     if len(mapmatrizes) > 0:

Modified: grass/trunk/lib/python/temporal/space_time_datasets.py
===================================================================
--- grass/trunk/lib/python/temporal/space_time_datasets.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/space_time_datasets.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -9,8 +9,8 @@
 :authors: Soeren Gebbert
 """
 import getpass
-from abstract_map_dataset import *
-from abstract_space_time_dataset import *
+from .abstract_map_dataset import *
+from .abstract_space_time_dataset import *
 import grass.script.array as garray
 
 ###############################################################################

Modified: grass/trunk/lib/python/temporal/spatial_extent.py
===================================================================
--- grass/trunk/lib/python/temporal/spatial_extent.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/spatial_extent.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -33,7 +33,8 @@
 
 :authors: Soeren Gebbert
 """
-from base import *
+from __future__ import print_function
+from .base import *
 
 
 class SpatialExtent(SQLDatabaseInterface):
@@ -1782,22 +1783,22 @@
     def print_info(self):
         """Print information about this class in human readable style"""
         #      0123456789012345678901234567890
-        print " +-------------------- Spatial extent ----------------------------------------+"
-        print " | North:...................... " + str(self.get_north())
-        print " | South:...................... " + str(self.get_south())
-        print " | East:.. .................... " + str(self.get_east())
-        print " | West:....................... " + str(self.get_west())
-        print " | Top:........................ " + str(self.get_top())
-        print " | Bottom:..................... " + str(self.get_bottom())
+        print(" +-------------------- Spatial extent ----------------------------------------+")
+        print(" | North:...................... " + str(self.get_north()))
+        print(" | South:...................... " + str(self.get_south()))
+        print(" | East:.. .................... " + str(self.get_east()))
+        print(" | West:....................... " + str(self.get_west()))
+        print(" | Top:........................ " + str(self.get_top()))
+        print(" | Bottom:..................... " + str(self.get_bottom()))
 
     def print_shell_info(self):
         """Print information about this class in shell style"""
-        print "north=" + str(self.get_north())
-        print "south=" + str(self.get_south())
-        print "east=" + str(self.get_east())
-        print "west=" + str(self.get_west())
-        print "top=" + str(self.get_top())
-        print "bottom=" + str(self.get_bottom())
+        print("north=" + str(self.get_north()))
+        print("south=" + str(self.get_south()))
+        print("east=" + str(self.get_east()))
+        print("west=" + str(self.get_west()))
+        print("top=" + str(self.get_top()))
+        print("bottom=" + str(self.get_bottom()))
 
 
 ###############################################################################

Modified: grass/trunk/lib/python/temporal/spatial_topology_dataset_connector.py
===================================================================
--- grass/trunk/lib/python/temporal/spatial_topology_dataset_connector.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/spatial_topology_dataset_connector.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -14,6 +14,7 @@
 
 :authors: Soeren Gebbert
 """
+from __future__ import print_function
 import copy
 
 
@@ -68,7 +69,7 @@
             meet=a at P
             >>> rlist = tmr.get_spatial_relations()
             >>> if "COVER" in rlist.keys():
-            ...    print rlist["COVER"][0].get_id()
+            ...    print(rlist["COVER"][0].get_id())
             a at P
 
     """
@@ -318,54 +319,54 @@
     def print_spatial_topology_info(self):
         """Print information about this class in human readable style"""
 
-        print " +-------------------- Spatial Topology --------------------------------------+"
+        print(" +-------------------- Spatial Topology --------------------------------------+")
         #          0123456789012345678901234567890
         if self.equivalent is not None:
-            print " | Equivalent: ................ " + \
-                self._generate_map_list_string(self.equivalent)
+            print(" | Equivalent: ................ " +
+                  self._generate_map_list_string(self.equivalent))
         if self.cover is not None:
-            print " | Cover: ..................... " + \
-                self._generate_map_list_string(self.cover)
+            print(" | Cover: ..................... " +
+                  self._generate_map_list_string(self.cover))
         if self.covered is not None:
-            print " | Covered: ................... " + \
-                self._generate_map_list_string(self.covered)
+            print(" | Covered: ................... " +
+                  self._generate_map_list_string(self.covered))
         if self.overlap is not None:
-            print " | Overlap: ................... " + \
-                self._generate_map_list_string(self.overlap)
+            print(" | Overlap: ................... " +
+                  self._generate_map_list_string(self.overlap))
         if self.in_ is not None:
-            print " | In: ........................ " + \
-                self._generate_map_list_string(self.in_)
+            print(" | In: ........................ " +
+                  self._generate_map_list_string(self.in_))
         if self.contain is not None:
-            print " | Contain: ................... " + \
-                self._generate_map_list_string(self.contain)
+            print(" | Contain: ................... " +
+                  self._generate_map_list_string(self.contain))
         if self.meet is not None:
-            print " | Meet: ...................... " + \
-                self._generate_map_list_string(self.meet)
+            print(" | Meet: ...................... " +
+                  self._generate_map_list_string(self.meet))
 
     def print_spatial_topology_shell_info(self):
         """Print information about this class in shell style"""
 
         if self.equivalent is not None:
-            print "equivalent=" + self._generate_map_list_string(self.equivalent,
-                                                                 False)
+            print("equivalent=" + self._generate_map_list_string(self.equivalent,
+                                                                 False))
         if self.cover is not None:
-            print "cover=" + self._generate_map_list_string(
-                self.cover, False)
+            print("cover=" + self._generate_map_list_string(
+                  self.cover, False))
         if self.covered is not None:
-            print "covered=" + \
-                self._generate_map_list_string(self.covered, False)
+            print("covered=" +
+                  self._generate_map_list_string(self.covered, False))
         if self.overlap is not None:
-            print "overlap=" + \
-                self._generate_map_list_string(self.overlap)
+            print("overlap=" +
+                  self._generate_map_list_string(self.overlap))
         if self.in_ is not None:
-            print "in=" + \
-                self._generate_map_list_string(self.in_)
+            print("in=" +
+                  self._generate_map_list_string(self.in_))
         if self.contain is not None:
-            print "contain=" + \
-                self._generate_map_list_string(self.contain)
+            print("contain=" +
+                  self._generate_map_list_string(self.contain))
         if self.meet is not None:
-            print "meet=" + \
-                self._generate_map_list_string(self.meet)
+            print("meet=" +
+                  self._generate_map_list_string(self.meet))
 
 ###############################################################################
 

Modified: grass/trunk/lib/python/temporal/spatio_temporal_relationships.py
===================================================================
--- grass/trunk/lib/python/temporal/spatio_temporal_relationships.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/spatio_temporal_relationships.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -17,8 +17,8 @@
 
 :authors: Soeren Gebbert
 """
-from abstract_dataset import *
-from datetime_math import *
+from .abstract_dataset import *
+from .datetime_math import *
 import grass.lib.vector as vector
 import grass.lib.rtree as rtree
 import grass.lib.gis as gis
@@ -431,7 +431,7 @@
         sorted_maps = sorted(
             maps, key=AbstractDatasetComparisonKeyStartTime)
 
-        for i in xrange(len(sorted_maps) - 1):
+        for i in range(len(sorted_maps) - 1):
             sorted_maps[i].set_next(sorted_maps[i + 1])
 
         for map_ in sorted_maps:
@@ -491,7 +491,7 @@
 
         tree = rtree.RTreeCreateTree(-1, 0, dim)
 
-        for i in xrange(len(maps)):
+        for i in range(len(maps)):
 
             rect = self._map_to_rect(tree, maps[i], spatial)
             rtree.RTreeInsertRect(rect, i + 1, tree)
@@ -542,13 +542,13 @@
 
         list_ = gis.G_new_ilist()
 
-        for j in xrange(len(mapsB)):
+        for j in range(len(mapsB)):
 
             rect = self._map_to_rect(tree, mapsB[j], spatial)
             vector.RTreeSearch2(tree, rect, list_)
             rtree.RTreeFreeRect(rect)
 
-            for k in xrange(list_.contents.n_values):
+            for k in range(list_.contents.n_values):
                 i = list_.contents.value[k] - 1
 
                 # Get the temporal relationship

Modified: grass/trunk/lib/python/temporal/stds_export.py
===================================================================
--- grass/trunk/lib/python/temporal/stds_export.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/stds_export.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -30,9 +30,9 @@
 import tarfile
 import tempfile
 
-from space_time_datasets import *
-from factory import *
-from open_stds import *
+from .space_time_datasets import *
+from .factory import *
+from .open_stds import *
 import grass.script as gscript
 from grass.exceptions import CalledModuleError
 
@@ -52,7 +52,7 @@
 ############################################################################
 
 
-def _export_raster_maps_as_gdal(rows, tar, list_file, new_cwd, fs, format_, 
+def _export_raster_maps_as_gdal(rows, tar, list_file, new_cwd, fs, format_,
                                 type_):
     for row in rows:
         name = row["name"]

Modified: grass/trunk/lib/python/temporal/stds_import.py
===================================================================
--- grass/trunk/lib/python/temporal/stds_import.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/stds_import.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -33,10 +33,10 @@
 import os.path
 import tarfile
 
-from space_time_datasets import *
-from register import *
-import factory
-from factory import *
+from .space_time_datasets import *
+from .register import *
+from . import factory
+from .factory import *
 import grass.script as gscript
 from grass.exceptions import CalledModuleError
 
@@ -244,7 +244,7 @@
         temp_file = open(temp_name, "w")
         proj_name = os.path.abspath(proj_file_name)
 
-        # We need to convert projection strings generated 
+        # We need to convert projection strings generated
         # from other programms than g.proj into
         # new line format so that the grass file comparison function
         # can be used to compare the projections

Modified: grass/trunk/lib/python/temporal/temporal_algebra.py
===================================================================
--- grass/trunk/lib/python/temporal/temporal_algebra.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/temporal_algebra.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -367,7 +367,7 @@
     None || None
     A* =  if condition None  then  A  else  B
     C = A*
-    
+
     >>> p = tgis.TemporalAlgebraLexer()
     >>> p.build()
     >>> p.debug = True
@@ -390,7 +390,7 @@
     LexToken(LPAREN,'(',1,32)
     LexToken(NAME,'C',1,33)
     LexToken(RPAREN,')',1,34)
-    
+
     >>> p = tgis.TemporalAlgebraLexer()
     >>> p.build()
     >>> p.debug = True
@@ -412,7 +412,7 @@
     LexToken(COMMA,',',1,33)
     LexToken(NAME,'A',1,35)
     LexToken(RPAREN,')',1,36)
-    
+
     >>> p = tgis.TemporalAlgebraLexer()
     >>> p.build()
     >>> p.debug = True
@@ -438,6 +438,7 @@
     LexToken(RPAREN,')',1,48)
 
 """
+from __future__ import print_function
 
 try:
     import ply.lex as lex
@@ -448,17 +449,17 @@
 import os
 import copy
 import grass.pygrass.modules as pymod
-from space_time_datasets import *
-from factory import *
-from open_stds import *
-from temporal_operator import *
+from .space_time_datasets import *
+from .factory import *
+from .open_stds import *
+from .temporal_operator import *
 
 ##############################################################################
 
 class TemporalAlgebraLexer(object):
     """Lexical analyzer for the GRASS GIS temporal algebra"""
 
-    # Functions that defines an if condition, temporal buffering, snapping and 
+    # Functions that defines an if condition, temporal buffering, snapping and
     # selection of maps with temporal extent.
     conditional_functions = {
         'if'    : 'IF',
@@ -471,7 +472,7 @@
         'str3ds' : 'STR3DS',
         'stvds' : 'STVDS',
     }
-    
+
     # Variables with date and time strings
     datetime_functions = {
         'start_time'     : 'START_TIME',     # start time as HH::MM:SS
@@ -565,7 +566,7 @@
     t_T_REL_OPERATOR     = r'\{([a-zA-Z\| ])+\}'
     t_T_SELECT           = r':'
     t_T_NOT_SELECT       = r'!:'
-    t_LPAREN             = r'\('    
+    t_LPAREN             = r'\('
     t_RPAREN             = r'\)'
     t_COMMA              = r','
     t_CEQUALS            = r'=='
@@ -664,7 +665,7 @@
         while True:
              tok = self.lexer.token()
              if not tok: break
-             print tok
+             print(tok)
 
 ###############################################################################
 
@@ -736,7 +737,7 @@
         ('left', 'AND', 'OR', 'T_COMP_OPERATOR'), #2
         )
 
-    def __init__(self, pid=None, run = True, debug = False, spatial = False, 
+    def __init__(self, pid=None, run = True, debug = False, spatial = False,
                         null = False, register_null = False,  nprocs = 1):
         self.run = run
         self.debug = debug
@@ -761,45 +762,45 @@
     def __del__(self):
         if self.dbif.connected:
             self.dbif.close()
-            
+
     def setup_common_granularity(self,  expression,  stdstype = 'strds',  lexer = None):
         """Configure the temporal algebra to use the common granularity of all
              space time datasets in the expression to generate the map lists.
-             
+
              This function will analyze the expression to detect space time datasets
              and computes the common granularity from all granularities.
-          
+
              This granularity is then be used to generate the map lists. Hence, all
              maps from all STDS will have equidistant temporal extents. The only meaningful
              temporal relation is "equal".
-             
+
              :param expression: The algebra expression to analyze
-             
+
              :param lexer: The temporal algebra lexer (select, raster, voxel, vector) that should be used to
                                     parse the expression, default is TemporalAlgebraLexer
-             
+
              :return: True if successful, False otherwise
- 
+
         """
         l = lexer
         # Split the expression to ignore the left part
         expressions = expression.split("=")[1:]
         expression = " ".join(expressions)
-        
+
         # Check if spatio-temporal operators are present in the expression
         if "{" in expression or "}" in expression:
             self.msgr.error(_("Spatio temporal operators are not supported in granularity algebra mode"))
             return False
-            
+
         # detect all STDS
         if l is None:
             l = TemporalAlgebraLexer()
         l.build()
         l.lexer.input(expression)
-        
+
         name_list = []
         tokens = []
-        
+
         count = 0
         while True:
             tok = l.lexer.token()
@@ -811,7 +812,7 @@
             if count > 1:
                 if tokens[count - 2] == "MAP" or tokens[count - 2] == "TMAP":
                     ignore = True
-            
+
             if tok.type == "NAME" and ignore == False:
                 name_list.append(tok.value)
             count += 1
@@ -831,23 +832,23 @@
             grans.append(stds.get_granularity())
             start_times.append(stds.get_temporal_extent_as_tuple()[0])
             ttypes[stds.get_temporal_type()] = stds.get_temporal_type()
-        
+
         # Only one temporal type is allowed
         if len(ttypes) > 1:
             self.msgr.error(_("All input space time datasets must have the same temporal type."))
             return False
-            
+
         # Compute the common granularity
         if "absolute" in ttypes.keys():
             self.granularity = compute_common_absolute_time_granularity(grans, start_times)
         else:
             self.granularity = compute_common_relative_time_granularity(grans)
-            
+
         self.use_granularity = True
-        
+
         return True
 
-    def parse(self, expression, stdstype = 'strds', maptype = 'rast',  mapclass = RasterDataset, 
+    def parse(self, expression, stdstype = 'strds', maptype = 'rast',  mapclass = RasterDataset,
                       basename = None, overwrite=False):
         self.lexer = TemporalAlgebraLexer()
         self.lexer.build()
@@ -877,7 +878,7 @@
         self.names[name] = name
         return name
 
-    def generate_new_map(self, base_map, bool_op = 'and', copy = True,  rename = True, 
+    def generate_new_map(self, base_map, bool_op = 'and', copy = True,  rename = True,
                                               remove = False):
         """Generate a new map using the spatio-temporal extent of the base map
 
@@ -967,7 +968,7 @@
                 if temp_ext != None:
                     mapA.set_temporal_extent(temp_ext)
                 else:
-                    returncode = 0                   
+                    returncode = 0
             elif temp_op == 'd':
                 temp_ext = mapA.temporal_disjoint_union(mapB)
                 if temp_ext != None:
@@ -983,25 +984,25 @@
         return(returncode)
 
     def set_temporal_extent_list(self, maplist, topolist = ["EQUAL"], temporal = 'l' ):
-        """ Change temporal extent of map list based on temporal relations to 
+        """ Change temporal extent of map list based on temporal relations to
                 other map list and given temporal operator.
 
-            :param maplist: List of map objects for which relations has been build 
+            :param maplist: List of map objects for which relations has been build
                                         correctely.
             :param topolist: List of strings of temporal relations.
             :param temporal: The temporal operator specifying the temporal
-                                            extent operation (intersection, union, disjoint 
+                                            extent operation (intersection, union, disjoint
                                             union, right reference, left reference).
 
             :return: Map list with specified temporal extent.
         """
         resultdict = {}
-        
+
         for map_i in maplist:
             # Loop over temporal related maps and create overlay modules.
             tbrelations = map_i.get_temporal_relations()
             # Generate an intermediate map for the result map list.
-            map_new = self.generate_new_map(base_map=map_i, bool_op = 'and', 
+            map_new = self.generate_new_map(base_map=map_i, bool_op = 'and',
                                                                         copy = True,  rename = True)
             # Combine temporal and spatial extents of intermediate map with related maps.
             for topo in topolist:
@@ -1009,7 +1010,7 @@
                     for map_j in (tbrelations[topo]):
                         if temporal == 'r':
                             # Generate an intermediate map for the result map list.
-                            map_new = self.generate_new_map(base_map=map_i, bool_op = 'and', 
+                            map_new = self.generate_new_map(base_map=map_i, bool_op = 'and',
                                                                                         copy = True,  rename = True)
                         # Create overlayed map extent.
                         returncode = self.overlay_map_extent(map_new, map_j, 'and', \
@@ -1024,10 +1025,10 @@
                             # print(map_new.cmd_list)
                             # resultlist.append(map_new)
                             resultdict[map_new.get_id()] = map_new
-        
+
                         # Create r.mapcalc expression string for the operation.
-                        #cmdstring = self.build_command_string(s_expr_a = map_new,  
-                        #                                                                s_expr_b = map_j,  
+                        #cmdstring = self.build_command_string(s_expr_a = map_new,
+                        #                                                                s_expr_b = map_j,
                         #                                                                operator = function)
                         # Conditional append of module command.
                         #map_new.cmd_list = cmdstring
@@ -1039,24 +1040,24 @@
         # Get sorted map objects as values from result dictionoary.
         resultlist = resultdict.values()
         resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
-        
+
         return(resultlist)
-    
+
     ######################### Temporal functions ##############################
 
     def remove_maps(self):
         """Removes empty or intermediate maps of different type.
         """
-        
+
         map_names = {}
         map_names["raster"] = []
         map_names["raster3d"] = []
         map_names["vector"] = []
-                
+
         if self.removable_maps:
             for map in self.removable_maps.values():
                     map_names[map.get_type()].append(map.get_name())
-        
+
         for key in map_names.keys():
             if map_names[key]:
                 self.msgr.message(_("Removing un-needed or empty %s maps"%(key)))
@@ -1064,7 +1065,7 @@
 
     def _remove_maps(self,  namelist,  map_type):
         """Remove maps of specific type
-        
+
             :param namelist: List of map names to be removed
             :param map_type: The type of the maps  (raster, raster_3d or vector)
         """
@@ -1072,13 +1073,13 @@
         chunklist = [namelist[i:i + max] for i in range(0, len(namelist), max)]
         for chunk in chunklist:
             stringlist = ",".join(chunk)
-            
+
             if self.run:
                 m = copy.deepcopy(self.m_mremove)
                 m.inputs["type"].value = map_type
                 m.inputs["name"].value = stringlist
                 m.flags["f"].value = True
-                print m.get_bash()
+                print(m.get_bash())
                 m.run()
 
     def check_stds(self, input, clear = False,  stds_type = None,  check_type=True):
@@ -1087,7 +1088,7 @@
             :param input: Name of space time data set as string or list of maps.
             :param clear: Reset the stored conditional values to empty list.
             :param check_type: Check the type of the space time dataset to match the global stds type
-            :param stds_type: The type of the space time dataset to be opened, if not provided 
+            :param stds_type: The type of the space time dataset to be opened, if not provided
                                           then self.stdstype will be used
 
             :return: List of maps.
@@ -1143,7 +1144,7 @@
         elif isinstance(input,  self.mapclass):
             # Check if the input is a single map and return it as list with one entry.
             maplist = [input]
-        
+
         elif isinstance(input,  list):
             maplist = input
             # Create map_value as empty list item.
@@ -1158,19 +1159,19 @@
                     map_i.condition_value = []
         else:
             self.msgr.fatal(_("Wrong type of input " + str(input)))
-            
+
         # We generate a unique map id that will be used
-        # in the topology analysis, since the maplist can 
-        # contain maps with equal map ids 
+        # in the topology analysis, since the maplist can
+        # contain maps with equal map ids
         for map in maplist:
             map.uid = self.generate_map_name()
             if self.debug:
-                print map.get_name(), map.uid,  map.get_temporal_extent_as_tuple()
-        
+                print(map.get_name(), map.uid,  map.get_temporal_extent_as_tuple())
+
         return(maplist)
 
     def get_temporal_topo_list(self, maplistA, maplistB = None, topolist = ["EQUAL"],
-                               assign_val = False, count_map = False, compare_bool = False,  
+                               assign_val = False, count_map = False, compare_bool = False,
                                compop = None, aggregate = None):
         """Build temporal topology for two space time data sets, copy map objects
           for given relation into map list.
@@ -1187,7 +1188,7 @@
                             related map list and compariosn operator.
           :param compop: Comparison operator, && or ||.
           :param aggregate: Aggregation operator for relation map list, & or |.
-          
+
           :return: List of maps from maplistA that fulfil the topological relationships
                   to maplistB specified in topolist.
 
@@ -1215,8 +1216,8 @@
               >>> for map in resultlist:
               ...     if map.get_equal():
               ...         relations = map.get_equal()
-              ...         print "Map %s has equal relation to map %s"%(map.get_name(),
-              ...               relations[0].get_name())
+              ...         print("Map %s has equal relation to map %s"%(map.get_name(),
+              ...               relations[0].get_name()))
               Map a0 has equal relation to map b0
               Map a1 has equal relation to map b1
               Map a2 has equal relation to map b2
@@ -1248,8 +1249,8 @@
               >>> for map in resultlist:
               ...     if map.get_starts():
               ...         relations = map.get_starts()
-              ...         print "Map %s has start relation to map %s"%(map.get_name(),
-              ...               relations[0].get_name())
+              ...         print("Map %s has start relation to map %s"%(map.get_name(),
+              ...               relations[0].get_name()))
               Map a0 has start relation to map b0
               Map a1 has start relation to map b1
               Map a2 has start relation to map b2
@@ -1263,8 +1264,8 @@
               >>> for map in resultlist:
               ...     if map.get_during():
               ...         relations = map.get_during()
-              ...         print "Map %s has during relation to map %s"%(map.get_name(),
-              ...               relations[0].get_name())
+              ...         print("Map %s has during relation to map %s"%(map.get_name(),
+              ...               relations[0].get_name()))
               Map a0 has during relation to map b0
               Map a1 has during relation to map b0
               Map a2 has during relation to map b1
@@ -1366,22 +1367,22 @@
                     # Use unique identifier, since map names may be equal
                     resultdict[map_i.uid] = map_i
         resultlist = resultdict.values()
-        
+
         # Sort list of maps chronological.
         resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
-        
+
         return(resultlist)
-    
+
     def assign_bool_value(self,  map_i, tbrelations, topolist = ["EQUAL"]):
-        """ Function to assign boolean map value based on the map_values from the 
+        """ Function to assign boolean map value based on the map_values from the
                 compared map list by topological relationships.
-                
+
           :param map_i: Map object with temporal extent.
           :param tbrelations: List of temporal relation to map_i.
           :param topolist: List of strings for given temporal relations.
-          
-          :return: Map object with conditional value that has been assigned by 
-                        relation maps that fulfil the topological relationships to 
+
+          :return: Map object with conditional value that has been assigned by
+                        relation maps that fulfil the topological relationships to
                         maplistB specified in topolist.
         """
         condition_value_list = []
@@ -1400,19 +1401,19 @@
         else:
             resultbool = False
         map_i.condition_value = [resultbool]
-        
+
         return(resultbool)
 
     def compare_bool_value(self,  map_i, tbrelations, compop, aggregate,  topolist = ["EQUAL"]):
-        """ Function to evaluate two map lists with boolean values by boolean 
-            comparison operator. 
-            
+        """ Function to evaluate two map lists with boolean values by boolean
+            comparison operator.
+
           :param map_i: Map object with temporal extent.
           :param tbrelations: List of temporal relation to map_i.
           :param topolist: List of strings for given temporal relations.
           :param compop: Comparison operator, && or ||.
           :param aggregate: Aggregation operator for relation map list, & or |.
-          
+
           :return: Map object with conditional value that has been evaluated by
                         comparison operators.
         """
@@ -1444,20 +1445,20 @@
             print(resultbool)
         # Add boolean value to result list.
         map_i.condition_value = [resultbool]
-        
+
         return(resultbool)
-    
+
     def eval_toperator(self, operator, optype = 'relation'):
         """This function evaluates a string containing temporal operations.
 
          :param operator: String of temporal operations, e.g. {!=,equal|during,l}.
          :param optype: String to define operator type.
-         
+
          :return :List of temporal relations (equal, during), the given function
           (!:) and the interval/instances (l).
-          
+
         .. code-block:: python
-        
+
              >>> import grass.temporal as tgis
              >>> tgis.init()
              >>> p = tgis.TemporalOperatorParser()
@@ -1470,7 +1471,7 @@
         p = TemporalOperatorParser()
         p.parse(operator, optype)
         p.relations = [rel.upper() for rel in p.relations]
-        
+
         return(p.relations, p.temporal, p.function,  p.aggregate)
 
     def perform_temporal_selection(self, maplistA, maplistB, topolist = ["EQUAL"],
@@ -1515,8 +1516,8 @@
               >>> for map in resultlist:
               ...     if map.get_equal():
               ...         relations = map.get_equal()
-              ...         print "Map %s has equal relation to map %s"%(map.get_name(),
-              ...               relations[0].get_name())
+              ...         print("Map %s has equal relation to map %s"%(map.get_name(),
+              ...               relations[0].get_name()))
               Map a5 has equal relation to map b0
               Map a6 has equal relation to map b1
               Map a7 has equal relation to map b2
@@ -1526,7 +1527,7 @@
               ...                                           True)
               >>> for map in resultlist:
               ...     if not map.get_equal():
-              ...         print "Map %s has no equal relation to mapset mapsB"%(map.get_name())
+              ...         print("Map %s has no equal relation to mapset mapsB"%(map.get_name()))
               Map a0 has no equal relation to mapset mapsB
               Map a1 has no equal relation to mapset mapsB
               Map a2 has no equal relation to mapset mapsB
@@ -1662,7 +1663,7 @@
             if unchanged == True:
                 if self.debug:
                     print('Leave temporal extend of result map: ' +  map_i.get_map_id() + ' unchanged.')
-        
+
         resultlist = resultdict.values()
         # Sort list of maps chronological.
         resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
@@ -1682,7 +1683,7 @@
           :return: Dictionary with temporal functions for given input map.
 
           .. code-block:: python
-          
+
               >>> import grass.temporal as tgis
               >>> import datetime
               >>> tgis.init()
@@ -1853,14 +1854,14 @@
         """ This function evaluates temporal variable expressions of a conditional
              expression in two steps.
              At first it combines stepwise the single conditions by their relations with LALR.
-             In this prossess sub condition map lists will be created which will include 
-             information of the underlying single conditions. Important: The temporal 
-             relations between conditions are evaluated by implicit aggregation. 
-             In the second step the aggregated condition map list will be compared with the 
+             In this prossess sub condition map lists will be created which will include
+             information of the underlying single conditions. Important: The temporal
+             relations between conditions are evaluated by implicit aggregation.
+             In the second step the aggregated condition map list will be compared with the
              map list of conclusion statements by the given temporal relation.
-             
-             The result is writen as 'condition_value' attribute to the resulting map objects. 
-             These attribute consists of boolean expressions and operators which can be 
+
+             The result is writen as 'condition_value' attribute to the resulting map objects.
+             These attribute consists of boolean expressions and operators which can be
              evaluated with the eval_condition_list function.
              [True,  '||', False, '&&', True]
 
@@ -1873,17 +1874,17 @@
 
              :param thenlist: Map list object of the conclusion statement.
                          It will be compared and evaluated by the conditions.
-          
-             :param topolist: List of temporal relations between the conditions and the 
+
+             :param topolist: List of temporal relations between the conditions and the
                          conclusions.
-                          
+
              :return: Map list with conditional values for all temporal expressions.
 
         """
-        
-        # Evaluate the temporal variable expression and compute the temporal combination 
+
+        # Evaluate the temporal variable expression and compute the temporal combination
         # of conditions.
-        
+
         # Check if the input expression is a valid single global variable.
         if isinstance(tvarexpr, GlobalTemporalVar) and tvarexpr.get_type() == "global" :
             # Use method eval_global_var to evaluate expression.
@@ -1930,14 +1931,14 @@
         resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
 
         return(resultlist)
-        
+
     def eval_condition_list(self, maplist, inverse = False):
         """ This function evaluates conditional values of a map list.
              A recursive function is used to evaluate comparison statements
              from left to right in the given conditional list.
 
-             For example: 
-            
+             For example:
+
                   - [True,  '||', False, '&&', True]  -> True
                   - [True,  '||', False, '&&', False] -> False
                   - [True,  '&&', False, '&&', True]  -> False
@@ -2021,12 +2022,12 @@
             if isinstance(t[3], list):
                 num = len(t[3])
                 count = 0
-                register_list = []      
+                register_list = []
                 if num > 0:
                     process_queue = pymod.ParallelModuleQueue(int(self.nprocs))
                     for map_i in t[3]:
-                        # Test if temporal extents have been changed by temporal 
-                        # relation operators (i|r). 
+                        # Test if temporal extents have been changed by temporal
+                        # relation operators (i|r).
                         if count == 0:
                             maps_stds_type = map_i.get_new_stds_instance(None).get_type()
                             map_type = map_i.get_type()
@@ -2082,14 +2083,14 @@
 
                     # Wait for running processes
                     process_queue.wait()
-                    
+
                     # Open connection to temporal database.
-                    # Create result space time dataset based on the map stds type        
+                    # Create result space time dataset based on the map stds type
                     resultstds = open_new_stds(t[1],maps_stds_type, \
                                                              'absolute', t[1], t[1], \
                                                              'mean', self.dbif, \
-                                                             overwrite = self.overwrite)                            
-                    for map_i in register_list:                
+                                                             overwrite = self.overwrite)
+                    for map_i in register_list:
                         # Get meta data from grass database.
                         map_i.load()
                         # Check if temporal extents have changed and a new map was created
@@ -2119,7 +2120,7 @@
                     self.msgr.warning("Empty result space time dataset. "\
                                                   "No map has been registered in %s"  %(t[1] ))
                     # Open connection to temporal database.
-                    # Create result space time dataset.                        
+                    # Create result space time dataset.
                     resultstds = open_new_stds(t[1], self.stdstype, \
                                                              'absolute', t[1], t[1], \
                                                              'mean', dbif, \
@@ -2131,7 +2132,7 @@
             t[0] = t[3]
 
         if self.debug:
-            print t[1], "=", t[3]
+            print(t[1], "=", t[3])
 
     def p_stds_1(self, t):
         # Definition of a space time dataset
@@ -2152,7 +2153,7 @@
 
     def p_expr_strds_function(self, t):
         # Explicitly specify a space time raster dataset
-        # R = A : strds(B) 
+        # R = A : strds(B)
         """
         expr : STRDS LPAREN stds RPAREN
         """
@@ -2161,11 +2162,11 @@
         else:
             t[0] = t[3]
             if self.debug:
-                print "Opening STRDS: ",  t[0]
+                print("Opening STRDS: ",  t[0])
 
     def p_expr_str3ds_function(self, t):
         # Explicitly specify a space time raster dataset
-        # R = A : str3ds(B) 
+        # R = A : str3ds(B)
         """
         expr : STR3DS LPAREN stds RPAREN
         """
@@ -2174,28 +2175,28 @@
         else:
             t[0] = t[3]
             if self.debug:
-                print "Opening STR3DS: ",  t[0]
+                print("Opening STR3DS: ",  t[0])
 
     def p_expr_stvds_function(self, t):
         # Explicitly specify a space time vector dataset
-        # R = A : stvds(B) 
+        # R = A : stvds(B)
         """
         expr : STVDS LPAREN stds RPAREN
         """
         if self.run:
-            print t[3]
+            print(t[3])
             t[0] = self.check_stds(t[3], stds_type = "stvds",  check_type=False)
         else:
             t[0] = t[3]
             if self.debug:
-                print "Opening STVDS: ",  t[0]
+                print("Opening STVDS: ",  t[0])
 
     def p_expr_tmap_function(self, t):
         # Add a single map.
-        # Only the spatial extent of the map is evaluated. 
+        # Only the spatial extent of the map is evaluated.
         # Temporal extent is not existing.
         # Examples:
-        #    R = tmap(A) 
+        #    R = tmap(A)
         """
         expr : TMAP LPAREN stds RPAREN
         """
@@ -2227,7 +2228,7 @@
             t[0] = "tmap(",  t[3] , ")"
 
         if self.debug:
-            print "tmap(", t[3] , ")"
+            print("tmap(", t[3] , ")")
 
     def p_expr_tmerge_function(self, t):
         # Merge two maplists of same STDS type into a result map list.
@@ -2244,7 +2245,7 @@
             # Check input map.
             maplistA   = self.check_stds(t[3])
             maplistB   = self.check_stds(t[5])
-            
+
             # Check empty lists.
             if len(maplistA) == 0 and len(maplistB) == 0:
                 self.msgr.warning(_("Merging empty map lists"))
@@ -2264,14 +2265,14 @@
                     grass.fatal(_("Space time datasets to merge must have the same temporal type"))
 
                 resultlist = maplistA + maplistB
-            
+
             # Return map list.
             t[0] = resultlist
         else:
             t[0] = "merge(",  t[3], ",", t[5], ")"
 
         if self.debug:
-            print "merge(", t[3], ",", t[5], ")"
+            print("merge(", t[3], ",", t[5], ")")
 
     def p_t_hash(self,t):
         """
@@ -2332,7 +2333,7 @@
             t[0] = "td(" + str(t[3]) + ")"
 
         if self.debug:
-            print "td(" + str(t[3]) + ")"
+            print("td(" + str(t[3]) + ")")
 
 
     def p_t_time_var(self, t):
@@ -2396,11 +2397,11 @@
                         map_i.condition_value = boolname
                 except:
                     self.msgr.fatal("Error: the given expression does not contain a correct time difference object.")
-            
+
             t[0] = maplist
-            
+
         if self.debug:
-            print t[1], t[2], t[3]
+            print(t[1], t[2], t[3])
 
     def p_t_var_expr_number(self, t):
         # Examples:
@@ -2409,7 +2410,7 @@
         #    start_day(B) < start_month(A)
         """
         t_var_expr : t_var LPAREN stds RPAREN comp_op number
-                | t_var LPAREN expr RPAREN comp_op number      
+                | t_var LPAREN expr RPAREN comp_op number
         """
         # TODO:  Implement comparison operator for map lists.
         #| t_var LPAREN stds RPAREN comp_op t_var LPAREN stds RPAREN
@@ -2429,7 +2430,7 @@
             t[0] = resultlist
 
         if self.debug:
-                print t[1], t[3], t[5], t[6]
+                print(t[1], t[3], t[5], t[6])
 
     def p_t_var_expr_time(self, t):
         # Examples:
@@ -2462,12 +2463,12 @@
             gvar.value  = t[6]
             # Evaluate temporal variable for given maplist.
             resultlist = self.eval_global_var(gvar, maplist)
-            
+
             t[0] = resultlist
 
 
         if self.debug:
-            print t[1], t[3],  t[5], t[6]
+            print(t[1], t[3],  t[5], t[6])
 
     def p_t_var_expr_comp(self, t):
         """
@@ -2481,18 +2482,18 @@
             relations = ["EQUAL"]
             temporal = "l"
             function = t[2] + t[3]
-            aggregate = t[2] 
-            # Build conditional values based on topological relationships.            
+            aggregate = t[2]
+            # Build conditional values based on topological relationships.
             complist = self.get_temporal_topo_list(tvarexprA, tvarexprB, topolist = relations,
                                compare_bool = True, compop = function[0], aggregate = aggregate)
             # Set temporal extent based on topological relationships.
-            resultlist = self.set_temporal_extent_list(complist, topolist = relations, 
+            resultlist = self.set_temporal_extent_list(complist, topolist = relations,
                                 temporal = temporal)
-            
+
             t[0] = resultlist
 
         if self.debug:
-            print t[1], t[2] + t[3], t[4]
+            print(t[1], t[2] + t[3], t[4])
 
     def p_t_var_expr_comp_op(self, t):
         """
@@ -2507,13 +2508,13 @@
             complist = self.get_temporal_topo_list(tvarexprA, tvarexprB, topolist = relations,
                                compare_bool = True, compop = function[0], aggregate = aggregate)
             # Set temporal extent based on topological relationships.
-            resultlist = self.set_temporal_extent_list(complist, topolist = relations, 
+            resultlist = self.set_temporal_extent_list(complist, topolist = relations,
                                 temporal = temporal)
 
             t[0] = resultlist
 
         if self.debug:
-            print t[1], t[2], t[3]
+            print(t[1], t[2], t[3])
 
     def p_expr_t_select(self, t):
         # Temporal equal selection
@@ -2540,7 +2541,7 @@
             t[0] = t[1] , "*"
 
         if self.debug:
-            print str(t[1]),  "* = ", t[1], t[2], t[3]
+            print(str(t[1]),  "* = ", t[1], t[2], t[3])
 
     def p_expr_t_not_select(self, t):
         # Temporal equal selection
@@ -2566,7 +2567,7 @@
             t[0] = t[1] + "*"
 
         if self.debug:
-            print t[1] + "* = ", t[1], t[2], t[3]
+            print(t[1] + "* = ", t[1], t[2], t[3])
 
 
     def p_expr_t_select_operator(self, t):
@@ -2599,7 +2600,7 @@
             # Perform selection.
             selectlist = self.perform_temporal_selection(maplistA, maplistB,
                          topolist = operators[0], inverse = negation)
-            selectlist = self.set_granularity(selectlist, maplistB, operators[1], 
+            selectlist = self.set_granularity(selectlist, maplistB, operators[1],
                 operators[0])
             # Return map list.
             t[0] = selectlist
@@ -2607,7 +2608,7 @@
             t[0] = t[1] + "*"
 
         if self.debug:
-            print t[1] + "* = ", t[1], t[2], t[3]
+            print(t[1] + "* = ", t[1], t[2], t[3])
 
 
     def p_expr_condition_if(self, t):
@@ -2622,7 +2623,7 @@
             thenlist     = self.check_stds(t[5])
             # Get temporal conditional statement.
             tvarexpr     = t[3]
-            thencond     = self.build_condition_list(tvarexpr, thenlist)      
+            thencond     = self.build_condition_list(tvarexpr, thenlist)
             thenresult   = self.eval_condition_list(thencond)
             # Clear the map and conditional values of the map list.
             resultlist   = self.check_stds(thenresult, clear = True)
@@ -2632,7 +2633,7 @@
             t[0] = t[5] + "*"
 
         if self.debug:
-            print str(t[5]) + "* = ", "if condition", str(t[3]), ' then ', str(t[5])
+            print(str(t[5]) + "* = ", "if condition", str(t[3]), ' then ', str(t[5]))
 
     def p_expr_condition_if_relation(self, t):
         # Examples
@@ -2647,8 +2648,8 @@
             # Get temporal conditional statement.
             tvarexpr     = t[5]
             topolist     = self.eval_toperator(t[3],  optype = 'relation')[0]
-            thencond     = self.build_condition_list(tvarexpr, thenlist, topolist)            
-            thenresult   = self.eval_condition_list(thencond)          
+            thencond     = self.build_condition_list(tvarexpr, thenlist, topolist)
+            thenresult   = self.eval_condition_list(thencond)
             # Clear the map and conditional values of the map list.
             resultlist   = self.check_stds(thenresult, clear = True)
             # Return resulting map list.
@@ -2657,7 +2658,7 @@
             t[0] = t[7] + "*"
 
         if self.debug:
-            print "result* = ", "if ", str(t[3]),  "condition", str(t[5]), " then ", str(t[7])
+            print("result* = ", "if ", str(t[3]),  "condition", str(t[5]), " then ", str(t[7]))
 
     def p_expr_condition_elif(self, t):
         # Examples
@@ -2690,7 +2691,7 @@
             t[0] = t[5] + "*"
 
         if self.debug:
-            print str(t[5]) + "* = ", "if condition", str(t[3]), " then ", str(t[5]), ' else ', str(t[7])
+            print(str(t[5]) + "* = ", "if condition", str(t[3]), " then ", str(t[5]), ' else ', str(t[7]))
 
     def p_expr_condition_elif_relation(self, t):
         # Examples
@@ -2730,9 +2731,9 @@
 
         if self.debug:
             if t[5]:
-                print str(t[7]), "* = ", "if condition", str(t[5]), " then ", str(t[7]), ' else ', str(t[9])
+                print(str(t[7]), "* = ", "if condition", str(t[5]), " then ", str(t[7]), ' else ', str(t[9]))
             else:
-                print str(t[9]), "* = ", "if condition", str(t[5]), " then ", str(t[7]), ' else ', str(t[9])
+                print(str(t[9]), "* = ", "if condition", str(t[5]), " then ", str(t[7]), ' else ', str(t[9]))
 
     def p_expr_t_buff(self, t):
         # Examples
@@ -2761,9 +2762,9 @@
 
         if self.debug:
             if len(t) == 10:
-                print str(t[3]) + "* = buff_t(", str(t[3]), "," , '"', str(t[6]), str(t[7]), '"', ")"
+                print(str(t[3]) + "* = buff_t(", str(t[3]), "," , '"', str(t[6]), str(t[7]), '"', ")")
             elif len(t) == 7:
-                print str(t[3]) + "* = buff_t(", str(t[3]), ",", str(t[5]), ")"
+                print(str(t[3]) + "* = buff_t(", str(t[3]), ",", str(t[5]), ")")
 
     def p_expr_t_snap(self, t):
         # Examples
@@ -2782,7 +2783,7 @@
             t[0] = t[3] + "*"
 
         if self.debug:
-            print str(t[3]) + "* = tsnap(", str(t[3]), ")"
+            print(str(t[3]) + "* = tsnap(", str(t[3]), ")")
 
     def p_expr_t_shift(self, t):
         # Examples
@@ -2810,9 +2811,9 @@
 
         if self.debug:
             if len(t) == 10:
-                print str(t[3]) + "* = tshift(", str(t[3]), "," , '"', str(t[6]), str(t[7]), '"', ")"
+                print(str(t[3]) + "* = tshift(", str(t[3]), "," , '"', str(t[6]), str(t[7]), '"', ")")
             elif len(t) == 7:
-                print str(t[3]) + "* = tshift(", str(t[3]), ",", str(t[5]), ")"
+                print(str(t[3]) + "* = tshift(", str(t[3]), ",", str(t[5]), ")")
 
     # Handle errors.
     def p_error(self, t):

Modified: grass/trunk/lib/python/temporal/temporal_extent.py
===================================================================
--- grass/trunk/lib/python/temporal/temporal_extent.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/temporal_extent.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -19,7 +19,8 @@
 
 :authors: Soeren Gebbert
 """
-from base import *
+from __future__ import print_function
+from .base import *
 
 ###############################################################################
 
@@ -156,13 +157,13 @@
                >>> A = TemporalExtent(start_time=5, end_time=8 )
                >>> B = TemporalExtent(start_time=3, end_time=4 )
                >>> inter = A.intersect(B)
-               >>> print inter
+               >>> print(inter)
                None
 
                >>> A = TemporalExtent(start_time=5, end_time=8 )
                >>> B = TemporalExtent(start_time=3, end_time=None )
                >>> inter = A.intersect(B)
-               >>> print inter
+               >>> print(inter)
                None
 
         """
@@ -396,13 +397,13 @@
                >>> A = TemporalExtent(start_time=5, end_time=8 )
                >>> B = TemporalExtent(start_time=3, end_time=4 )
                >>> inter = A.intersect(B)
-               >>> print inter
+               >>> print(inter)
                None
 
                >>> A = TemporalExtent(start_time=5, end_time=8 )
                >>> B = TemporalExtent(start_time=3, end_time=None )
                >>> inter = A.intersect(B)
-               >>> print inter
+               >>> print(inter)
                None
 
         """
@@ -1028,13 +1029,13 @@
     def print_info(self):
         """Print information about this class in human readable style"""
         #      0123456789012345678901234567890
-        print " | Start time:................. " + str(self.get_start_time())
-        print " | End time:................... " + str(self.get_end_time())
+        print(" | Start time:................. " + str(self.get_start_time()))
+        print(" | End time:................... " + str(self.get_end_time()))
 
     def print_shell_info(self):
         """Print information about this class in shell style"""
-        print "start_time=" + str(self.get_start_time())
-        print "end_time=" + str(self.get_end_time())
+        print("start_time=" + str(self.get_start_time()))
+        print("end_time=" + str(self.get_end_time()))
 
 ###############################################################################
 
@@ -1052,7 +1053,7 @@
     def print_info(self):
         """Print information about this class in human readable style"""
         #      0123456789012345678901234567890
-        print " +-------------------- Absolute time -----------------------------------------+"
+        print(" +-------------------- Absolute time -----------------------------------------+")
         TemporalExtent.print_info(self)
 
     def print_shell_info(self):
@@ -1177,14 +1178,14 @@
         """Print information about this class in human readable style"""
         AbsoluteTemporalExtent.print_info(self)
         #      0123456789012345678901234567890
-        print " | Granularity:................ " + str(self.get_granularity())
-        print " | Temporal type of maps:...... " + str(self.get_map_time())
+        print(" | Granularity:................ " + str(self.get_granularity()))
+        print(" | Temporal type of maps:...... " + str(self.get_map_time()))
 
     def print_shell_info(self):
         """Print information about this class in shell style"""
         AbsoluteTemporalExtent.print_shell_info(self)
-        print "granularity=" + str(self.get_granularity())
-        print "map_time=" + str(self.get_map_time())
+        print("granularity=" + str(self.get_granularity()))
+        print("map_time=" + str(self.get_map_time()))
 
 ###############################################################################
 
@@ -1294,14 +1295,14 @@
     def print_info(self):
         """Print information about this class in human readable style"""
         #      0123456789012345678901234567890
-        print " +-------------------- Relative time -----------------------------------------+"
+        print(" +-------------------- Relative time -----------------------------------------+")
         TemporalExtent.print_info(self)
-        print " | Relative time unit:......... " + str(self.get_unit())
+        print(" | Relative time unit:......... " + str(self.get_unit()))
 
     def print_shell_info(self):
         """Print information about this class in shell style"""
         TemporalExtent.print_shell_info(self)
-        print "unit=" + str(self.get_unit())
+        print("unit=" + str(self.get_unit()))
 
 ###############################################################################
 
@@ -1426,14 +1427,14 @@
         """Print information about this class in human readable style"""
         RelativeTemporalExtent.print_info(self)
         #      0123456789012345678901234567890
-        print " | Granularity:................ " + str(self.get_granularity())
-        print " | Temporal type of maps:...... " + str(self.get_map_time())
+        print(" | Granularity:................ " + str(self.get_granularity()))
+        print(" | Temporal type of maps:...... " + str(self.get_map_time()))
 
     def print_shell_info(self):
         """Print information about this class in shell style"""
         RelativeTemporalExtent.print_shell_info(self)
-        print "granularity=" + str(self.get_granularity())
-        print "map_time=" + str(self.get_map_time())
+        print("granularity=" + str(self.get_granularity()))
+        print("map_time=" + str(self.get_map_time()))
 
 ###############################################################################
 

Modified: grass/trunk/lib/python/temporal/temporal_granularity.py
===================================================================
--- grass/trunk/lib/python/temporal/temporal_granularity.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/temporal_granularity.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -17,8 +17,9 @@
 
 :authors: Soeren Gebbert
 """
-from abstract_dataset import *
-from datetime_math import *
+from .abstract_dataset import *
+from .datetime_math import *
+from functools import reduce
 
 ###############################################################################
 
@@ -497,7 +498,7 @@
 
 def compute_common_relative_time_granularity(gran_list):
 	"""Compute the greatest common granule from a list of relative time granules
-    
+
         .. code-block:: python
 
             >>> import grass.temporal as tgis
@@ -505,7 +506,7 @@
             >>> grans = [1,2,30]
             >>> tgis.compute_common_relative_time_granularity(grans)
             1
-            
+
             >>> import grass.temporal as tgis
             >>> tgis.init()
             >>> grans = [10,20,30]
@@ -756,23 +757,23 @@
             >>> grans = ["1 second", "2 seconds", "30 seconds"]
             >>> tgis.compute_common_absolute_time_granularity(grans)
             '1 second'
-            
+
             >>> grans = ["3 second", "6 seconds", "30 seconds"]
             >>> tgis.compute_common_absolute_time_granularity(grans)
             '3 seconds'
-            
+
             >>> grans = ["12 second", "18 seconds", "30 seconds", "10 minutes"]
             >>> tgis.compute_common_absolute_time_granularity(grans)
             '6 seconds'
-            
+
             >>> grans = ["20 second", "10 minutes", "2 hours"]
             >>> tgis.compute_common_absolute_time_granularity(grans)
             '20 seconds'
-            
+
             >>> grans = ["7200 second", "240 minutes", "1 year"]
             >>> tgis.compute_common_absolute_time_granularity(grans)
             '7200 seconds'
-            
+
             >>> grans = ["7200 second", "89 minutes", "1 year"]
             >>> tgis.compute_common_absolute_time_granularity(grans)
             '60 seconds'
@@ -821,37 +822,37 @@
             >>> tgis.compute_common_absolute_time_granularity(grans)
             '1 year'
     """
-    
+
     has_seconds = False # 0
     has_minutes = False # 1
     has_hours = False     # 2
     has_days = False      # 3
     has_months = False  # 4
     has_years = False     # 5
-    
+
     seconds = []
     minutes = []
     hours = []
     days = []
     months = []
     years = []
-    
+
     min_gran = 6
     max_gran = -1
-    
+
     for entry in gran_list:
         if not check_granularity_string(entry, "absolute"):
             return False
 
         num,  gran = entry.split()
-        
+
         if gran in ["seconds",  "second"]:
             has_seconds = True
             if min_gran > 0:
                 min_gran = 0
             if max_gran < 0:
                 max_gran = 0
-                
+
             seconds.append(int(num))
 
         if gran in ["minutes",  "minute"]:
@@ -860,7 +861,7 @@
                 min_gran = 1
             if max_gran < 1:
                 max_gran = 1
-                
+
             minutes.append(int(num))
 
         if gran in ["hours",  "hour"]:
@@ -869,7 +870,7 @@
                 min_gran = 2
             if max_gran < 2:
                 max_gran = 2
-                
+
             hours.append(int(num))
 
         if gran in ["days",  "day"]:
@@ -878,7 +879,7 @@
                 min_gran = 3
             if max_gran < 3:
                 max_gran = 3
-                
+
             days.append(int(num))
 
         if gran in ["months",  "month"]:
@@ -887,7 +888,7 @@
                 min_gran = 4
             if max_gran < 4:
                 max_gran = 4
-                
+
             months.append(int(num))
 
         if gran in ["years",  "year"]:
@@ -896,9 +897,9 @@
                 min_gran = 5
             if max_gran < 5:
                 max_gran = 5
-                
+
             years.append(int(num))
-            
+
     if has_seconds:
         if has_minutes:
             minutes.sort()
@@ -925,7 +926,7 @@
         if num > 1:
             gran += "s"
         return "%i %s"%(num,  gran)
-        
+
     elif has_minutes:
         if has_hours:
             hours.sort()
@@ -948,7 +949,7 @@
         if num > 1:
             gran += "s"
         return "%i %s"%(num,  gran)
-        
+
     elif has_hours:
         if has_days:
             days.sort()
@@ -995,15 +996,15 @@
         if num > 1:
             gran += "s"
         return "%i %s"%(num,  gran)
-        
+
     elif has_years:
         num = gcd_list(years)
         gran = "year"
         if num > 1:
             gran += "s"
         return "%i %s"%(num,  gran)
-        
 
+
 ###############################################################################
 # http://akiscode.com/articles/gcd_of_a_list.shtml
 # Copyright (c) 2010 Stephen Akiki

Modified: grass/trunk/lib/python/temporal/temporal_operator.py
===================================================================
--- grass/trunk/lib/python/temporal/temporal_operator.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/temporal_operator.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -14,95 +14,96 @@
     >>> p = TemporalOperatorParser()
     >>> expression =  "{equal| during}"
     >>> p.parse(expression, optype = 'relation')
-    >>> print(p.relations, p.temporal, p.function)
+    >>> print((p.relations, p.temporal, p.function))
     (['equal', 'during'], None, None)
-    >>> p = TemporalOperatorParser()    
+    >>> p = TemporalOperatorParser()
     >>> expression =  "{contains | starts}"
     >>> p.parse(expression)
-    >>> print(p.relations, p.temporal, p.function)
+    >>> print((p.relations, p.temporal, p.function))
     (['contains', 'starts'], None, None)
-    >>> p = TemporalOperatorParser()    
+    >>> p = TemporalOperatorParser()
     >>> expression =  "{&&, during}"
     >>> p.parse(expression, optype = 'boolean')
-    >>> print(p.relations, p.temporal, p.function,p.aggregate)
+    >>> print((p.relations, p.temporal, p.function,p.aggregate))
     (['during'], 'l', '&&', '&')
-    >>> p = TemporalOperatorParser()    
+    >>> p = TemporalOperatorParser()
     >>> expression =  "{||, equal | during}"
     >>> p.parse(expression, optype = 'boolean')
-    >>> print(p.relations, p.temporal, p.function,p.aggregate)
+    >>> print((p.relations, p.temporal, p.function,p.aggregate))
     (['equal', 'during'], 'l', '||', '|')
-    >>> p = TemporalOperatorParser()    
+    >>> p = TemporalOperatorParser()
     >>> expression =  "{||, equal | during, &}"
     >>> p.parse(expression, optype = 'boolean')
-    >>> print(p.relations, p.temporal, p.function,p.aggregate)
+    >>> print((p.relations, p.temporal, p.function,p.aggregate))
     (['equal', 'during'], 'l', '||', '&')
-    >>> p = TemporalOperatorParser()    
+    >>> p = TemporalOperatorParser()
     >>> expression =  "{&&, during, |}"
     >>> p.parse(expression, optype = 'boolean')
-    >>> print(p.relations, p.temporal, p.function,p.aggregate)
+    >>> print((p.relations, p.temporal, p.function,p.aggregate))
     (['during'], 'l', '&&', '|')
-    >>> p = TemporalOperatorParser()    
+    >>> p = TemporalOperatorParser()
     >>> expression =  "{&&, during, |, r}"
     >>> p.parse(expression, optype = 'boolean')
-    >>> print(p.relations, p.temporal, p.function,p.aggregate)
+    >>> print((p.relations, p.temporal, p.function,p.aggregate))
     (['during'], 'r', '&&', '|')
-    >>> p = TemporalOperatorParser()    
+    >>> p = TemporalOperatorParser()
     >>> expression =  "{&&, during, u}"
     >>> p.parse(expression, optype = 'boolean')
-    >>> print(p.relations, p.temporal, p.function,p.aggregate)
+    >>> print((p.relations, p.temporal, p.function,p.aggregate))
     (['during'], 'u', '&&', '&')
-    >>> p = TemporalOperatorParser()    
+    >>> p = TemporalOperatorParser()
     >>> expression =  "{:, during, r}"
     >>> p.parse(expression, optype = 'select')
-    >>> print(p.relations, p.temporal, p.function)
+    >>> print((p.relations, p.temporal, p.function))
     (['during'], 'r', ':')
-    >>> p = TemporalOperatorParser()    
+    >>> p = TemporalOperatorParser()
     >>> expression =  "{!:, equal | contains, d}"
     >>> p.parse(expression, optype = 'select')
-    >>> print(p.relations, p.temporal, p.function)
+    >>> print((p.relations, p.temporal, p.function))
     (['equal', 'contains'], 'd', '!:')
-    >>> p = TemporalOperatorParser()    
+    >>> p = TemporalOperatorParser()
     >>> expression =  "{#, during, r}"
     >>> p.parse(expression, optype = 'hash')
-    >>> print(p.relations, p.temporal, p.function)
+    >>> print((p.relations, p.temporal, p.function))
     (['during'], 'r', '#')
-    >>> p = TemporalOperatorParser()    
+    >>> p = TemporalOperatorParser()
     >>> expression =  "{#, equal | contains}"
     >>> p.parse(expression, optype = 'hash')
-    >>> print(p.relations, p.temporal, p.function)
+    >>> print((p.relations, p.temporal, p.function))
     (['equal', 'contains'], 'l', '#')
-    >>> p = TemporalOperatorParser()    
+    >>> p = TemporalOperatorParser()
     >>> expression =  "{+, during, r}"
     >>> p.parse(expression, optype = 'raster')
-    >>> print(p.relations, p.temporal, p.function)
+    >>> print((p.relations, p.temporal, p.function))
     (['during'], 'r', '+')
-    >>> p = TemporalOperatorParser()    
+    >>> p = TemporalOperatorParser()
     >>> expression =  "{/, equal | contains}"
     >>> p.parse(expression, optype = 'raster')
-    >>> print(p.relations, p.temporal, p.function)
+    >>> print((p.relations, p.temporal, p.function))
     (['equal', 'contains'], 'l', '/')
-    >>> p = TemporalOperatorParser()    
+    >>> p = TemporalOperatorParser()
     >>> expression =  "{+, equal | contains,intersect}"
     >>> p.parse(expression, optype = 'raster')
-    >>> print(p.relations, p.temporal, p.function)
+    >>> print((p.relations, p.temporal, p.function))
     (['equal', 'contains'], 'i', '+')
-    >>> p = TemporalOperatorParser()    
+    >>> p = TemporalOperatorParser()
     >>> expression =  "{*, contains,disjoint}"
     >>> p.parse(expression, optype = 'raster')
-    >>> print(p.relations, p.temporal, p.function)
+    >>> print((p.relations, p.temporal, p.function))
     (['contains'], 'd', '*')
-    >>> p = TemporalOperatorParser()    
+    >>> p = TemporalOperatorParser()
     >>> expression =  "{~, equal,left}"
     >>> p.parse(expression, optype = 'overlay')
-    >>> print(p.relations, p.temporal, p.function)
+    >>> print((p.relations, p.temporal, p.function))
     (['equal'], 'l', '~')
-    >>> p = TemporalOperatorParser()    
+    >>> p = TemporalOperatorParser()
     >>> expression =  "{^, over,right}"
     >>> p.parse(expression, optype = 'overlay')
-    >>> print(p.relations, p.temporal, p.function)
+    >>> print((p.relations, p.temporal, p.function))
     (['overlaps', 'overlapped'], 'r', '^')
 
 """
+from __future__ import print_function
 
 try:
     import ply.lex as lex
@@ -134,7 +135,7 @@
         'COMMA',
         'LEFTREF',
         'RIGHTREF',
-        'UNION', 
+        'UNION',
         'DISJOINT',
         'INTERSECT',
         'HASH',
@@ -142,11 +143,11 @@
         'AND',
         'DISOR',
         'XOR',
-        'NOT',        
+        'NOT',
         'MOD',
         'DIV',
         'MULT',
-        'ADD',      
+        'ADD',
         'SUB',
         'T_SELECT',
         'T_NOT_SELECT',
@@ -171,7 +172,7 @@
     t_AND                        = r'[&]'
     t_DISOR                     = r'\+'
     t_XOR                         = r'\^'
-    t_NOT                         = r'\~'    
+    t_NOT                         = r'\~'
     t_MOD                       = r'[\%]'
     t_DIV                         = r'[\/]'
     t_MULT                      = r'[\*]'
@@ -234,7 +235,7 @@
         while True:
              tok = self.lexer.token()
              if not tok: break
-             print tok
+             print(tok)
 
 ###############################################################################
 
@@ -251,19 +252,19 @@
         self.aggregate = None
 
     def parse(self, expression,  optype = 'relation'):
-        self.optype = optype        
+        self.optype = optype
         self.parser.parse(expression)
-        # The parameter optype can be of type: select {:, during, r}, boolean{&&, contains, |}, 
+        # The parameter optype can be of type: select {:, during, r}, boolean{&&, contains, |},
         #                                                            raster{*, equal, |}, vector {|, starts, &},
         #                                                            hash{#, during, l} or relation {during}.
-    
+
     # Error rule for syntax errors.
     def p_error(self, t):
         raise SyntaxError("Unexpected syntax error")
 
     # Get the tokens from the lexer class
     tokens = TemporalOperatorLexer.tokens
- 
+
     def p_relation_operator(self, t):
         # The expression should always return a list of maps.
         """
@@ -294,7 +295,7 @@
         """
         if not self.optype == 'boolean':
             raise SyntaxError("invalid syntax")
-        else:        
+        else:
             # Set three operator components.
             if isinstance(t[5], list):
                 self.relations = t[5]
@@ -303,7 +304,7 @@
             self.temporal  = "l"
             self.function  = t[2] + t[3]
             self.aggregate = t[2]
-            
+
             t[0] = t[2]
 
     def p_relation_bool_combi_operator(self, t):
@@ -320,7 +321,7 @@
         """
         if not self.optype == 'boolean':
             raise SyntaxError("invalid syntax")
-        else:        
+        else:
             # Set three operator components.
             if isinstance(t[5], list):
                 self.relations = t[5]
@@ -329,7 +330,7 @@
             self.temporal  = "l"
             self.function  = t[2] + t[3]
             self.aggregate = t[7]
-            
+
             t[0] = t[2]
 
     def p_relation_bool_combi_operator2(self, t):
@@ -342,7 +343,7 @@
         """
         if not self.optype == 'boolean':
             raise SyntaxError("invalid syntax")
-        else:        
+        else:
             # Set three operator components.
             if isinstance(t[5], list):
                 self.relations = t[5]
@@ -351,9 +352,9 @@
             self.temporal  = t[7]
             self.function  = t[2] + t[3]
             self.aggregate = t[2]
-            
+
             t[0] = t[2]
-    
+
     def p_relation_bool_combi_operator3(self, t):
         # The expression should always return a list of maps.
         """
@@ -368,7 +369,7 @@
         """
         if not self.optype == 'boolean':
             raise SyntaxError("invalid syntax")
-        else:        
+        else:
             # Set three operator components.
             if isinstance(t[5], list):
                 self.relations = t[5]
@@ -377,9 +378,9 @@
             self.temporal  = t[9]
             self.function  = t[2] + t[3]
             self.aggregate = t[7]
-            
+
             t[0] = t[2]
-    
+
     def p_select_relation_operator(self, t):
         # The expression should always return a list of maps.
         """
@@ -612,4 +613,3 @@
 if __name__ == "__main__":
     import doctest
     doctest.testmod()
-

Modified: grass/trunk/lib/python/temporal/temporal_raster3d_algebra.py
===================================================================
--- grass/trunk/lib/python/temporal/temporal_raster3d_algebra.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/temporal_raster3d_algebra.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -10,10 +10,8 @@
 :authors: Thomas Leppelt and Soeren Gebbert
 
 """
+from .temporal_raster_base_algebra import *
 
-import grass.pygrass.modules as pygrass
-from temporal_raster_base_algebra import *
-
 ###############################################################################
 
 class TemporalRaster3DAlgebraParser(TemporalRasterBaseAlgebraParser):
@@ -34,7 +32,7 @@
         while True:
             tok = l.lexer.token()
             if not tok: break
-            
+
             if tok.type == "STVDS" or tok.type == "STRDS" or tok.type == "STR3DS":
                 raise SyntaxError("Syntax error near '%s'" %(tok.type))
 

Modified: grass/trunk/lib/python/temporal/temporal_raster_algebra.py
===================================================================
--- grass/trunk/lib/python/temporal/temporal_raster_algebra.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/temporal_raster_algebra.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -52,7 +52,7 @@
 
 """
 
-from temporal_raster_base_algebra import *
+from .temporal_raster_base_algebra import *
 
 ###############################################################################
 
@@ -74,10 +74,10 @@
         while True:
             tok = l.lexer.token()
             if not tok: break
-            
+
             if tok.type == "STVDS" or tok.type == "STRDS" or tok.type == "STR3DS":
                 raise SyntaxError("Syntax error near '%s'" %(tok.type))
-        
+
         self.lexer = TemporalRasterAlgebraLexer()
         self.lexer.build()
         self.parser = yacc.yacc(module=self, debug=self.debug)

Modified: grass/trunk/lib/python/temporal/temporal_raster_base_algebra.py
===================================================================
--- grass/trunk/lib/python/temporal/temporal_raster_base_algebra.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/temporal_raster_base_algebra.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -16,7 +16,7 @@
     >>> p.debug = True
     >>> expression =  'R = A {+,equal,l} B '
     >>> p.test(expression)
-    R = A {+,equal,l} B 
+    R = A {+,equal,l} B
     LexToken(NAME,'R',1,0)
     LexToken(EQUALS,'=',1,2)
     LexToken(NAME,'A',1,4)
@@ -24,7 +24,7 @@
     LexToken(NAME,'B',1,18)
     >>> expression =  'R = A {*,equal|during,r} B '
     >>> p.test(expression)
-    R = A {*,equal|during,r} B 
+    R = A {*,equal|during,r} B
     LexToken(NAME,'R',1,0)
     LexToken(EQUALS,'=',1,2)
     LexToken(NAME,'A',1,4)
@@ -32,7 +32,7 @@
     LexToken(NAME,'B',1,25)
     >>> expression =  'R = A {+,equal|during} B '
     >>> p.test(expression)
-    R = A {+,equal|during} B 
+    R = A {+,equal|during} B
     LexToken(NAME,'R',1,0)
     LexToken(EQUALS,'=',1,2)
     LexToken(NAME,'A',1,4)
@@ -40,10 +40,10 @@
     LexToken(NAME,'B',1,23)
 
 """
-
+from __future__ import print_function
 import grass.pygrass.modules as pymod
-from temporal_operator import *
-from temporal_algebra import *
+from .temporal_operator import *
+from .temporal_algebra import *
 
 ##############################################################################
 
@@ -70,12 +70,12 @@
         'isnull'  : 'ISNULL',
         'isntnull': 'ISNTNULL',
         'null'    : 'NULL',
-        'exist'   : 'EXIST',   
+        'exist'   : 'EXIST',
     }
-    
+
     # Functions that defines single maps with time stamp and without temporal extent.
     map_functions = {'map' : 'MAP'}
-    
+
     # This is the list of token names.
     raster_tokens = (
         'MOD',
@@ -153,12 +153,12 @@
 
     ######################### Temporal functions ##############################
     def get_temporal_topo_list(self, maplistA, maplistB = None, topolist = ["EQUAL"],
-                               assign_val = False, count_map = False, compare_bool = False,  
-                               compare_cmd = False,  compop = None, aggregate = None,  
+                               assign_val = False, count_map = False, compare_bool = False,
+                               compare_cmd = False,  compop = None, aggregate = None,
                                new = False,  convert = False,  operator_cmd = False):
         """Build temporal topology for two space time data sets, copy map objects
           for given relation into map list.
-          
+
           :param maplistA: List of maps.
           :param maplistB: List of maps.
           :param topolist: List of strings of temporal relations.
@@ -174,11 +174,11 @@
           :param compop: Comparison operator, && or ||.
           :param aggregate: Aggregation operator for relation map list, & or |.
           :param new: Boolean if new temporary maps should be created.
-          :param convert: Boolean if conditional values should be converted to 
+          :param convert: Boolean if conditional values should be converted to
                         r.mapcalc command strings.
-          :param operator_cmd: Boolean for aggregate arithmetic operators implicitly 
+          :param operator_cmd: Boolean for aggregate arithmetic operators implicitly
                         in command list values based on related map lists.
-                    
+
           :return: List of maps from maplistA that fulfil the topological relationships
                   to maplistB specified in topolist.
         """
@@ -219,7 +219,7 @@
                 self.compare_cmd_value(map_i,  tbrelations, compop, aggregate, topolist, convert)
             elif operator_cmd:
                 self.operator_cmd_value(map_i,  tbrelations, compop, topolist)
-                
+
             for topo in topolist:
                 if topo.upper() in tbrelations.keys():
                     if count_map:
@@ -233,30 +233,30 @@
                     # Use unique identifier, since map names may be equal
                     resultdict[map_i.uid] = map_i
         resultlist = resultdict.values()
-        
+
         # Sort list of maps chronological.
         resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
-        
-        return(resultlist)    
-    
+
+        return(resultlist)
+
     def build_command_string(self, map_i,  relmap, operator = None, cmd_type = None):
-        """This function build the r.mapcalc command string for conditionals, 
+        """This function build the r.mapcalc command string for conditionals,
             spatial variable combinations and boolean comparisons.
-            
+
             For Example: 'if(a1 == 1, b1, c2)' or 'exist(a1) && sin(b1)'
-            
+
             :param map_i: map object with temporal extent and built relations.
             :param relmap: map object with defined temporal relation to map_i.
-            :param operator: String representing operator between two spatial variables 
+            :param operator: String representing operator between two spatial variables
                             (&&,||,+,-,*,/).
             :param cmd_type: map object with defined temporal relation to map_i:
                             condition, conclusion or operator.
-            
-            :return: the resulting command string for conditionals or spatial variable 
+
+            :return: the resulting command string for conditionals or spatial variable
                 combinations
-        """    
+        """
         def sub_cmdstring(map_i):
-            """This function search for command string in a map object and 
+            """This function search for command string in a map object and
             return substitute string (contained commandstring or map name)"""
             if "cmd_list" in dir(map_i):
                 map_sub = map_i.cmd_list
@@ -268,8 +268,8 @@
                 except:
                     map_sub = map_i
             return(map_sub)
-        
-        # Check  for type of operation, conditional or spatial variable combination 
+
+        # Check  for type of operation, conditional or spatial variable combination
         # and Create r.mapcalc expression string for the operation.
         cmdstring = ""
         if cmd_type == 'condition':
@@ -289,18 +289,18 @@
             cmdstring = "(%s %s %s)" %(leftsub, operator,  rightsub)
         return(cmdstring)
 
-    def compare_cmd_value(self,  map_i, tbrelations, compop, aggregate,  
+    def compare_cmd_value(self,  map_i, tbrelations, compop, aggregate,
                                                 topolist = ["EQUAL"],  convert = False):
-        """ Function to evaluate two map lists with boolean values by boolean 
-            comparison operator. Extended temporal algebra version with command 
+        """ Function to evaluate two map lists with boolean values by boolean
+            comparison operator. Extended temporal algebra version with command
             list builder for temporal raster algebra.
-            
+
             :param map_i: Map object with temporal extent.
             :param tbrelations: List of temporal relation to map_i.
             :param topolist: List of strings for given temporal relations.
             :param compop: Comparison operator, && or ||.
             :param aggregate: Aggregation operator for relation map list, & or |.
-            :param convert: Boolean if conditional values should be converted to 
+            :param convert: Boolean if conditional values should be converted to
                         r.mapcalc command strings.
 
             :return: Map object with conditional value that has been evaluated by
@@ -315,7 +315,7 @@
             leftcmd = map_i.cmd_list
             cmd_value_list = [leftcmd]
         count = 0
-        
+
         for topo in topolist:
             if topo.upper() in tbrelations.keys():
                 relationmaplist = tbrelations[topo.upper()]
@@ -337,18 +337,18 @@
             cmd_value_str = ''.join(map(str, cmd_value_list))
             # Add command list to result map.
             map_i.cmd_list = cmd_value_str
-        
+
             return(cmd_value_str)
 
     def operator_cmd_value(self,  map_i, tbrelations, operator, topolist = ["EQUAL"]):
         """ Function to evaluate two map lists by given arithmetic operator.
-        
+
             :param map_i: Map object with temporal extent.
             :param tbrelations: List of temporal relation to map_i.
             :param topolist: List of strings for given temporal relations.
             :param operator: Arithmetic operator, +-*/%.
 
-            :return: Map object with command list with  operators that has been 
+            :return: Map object with command list with  operators that has been
                         evaluated by implicit aggregration.
         """
         # Build comandlist list with elements from related maps and given relation operator.
@@ -359,26 +359,26 @@
                 relationmaplist = tbrelations[topo.upper()]
                 for relationmap in relationmaplist:
                     # Create r.mapcalc expression string for the operation.
-                    cmdstring = self.build_command_string(leftcmd,  
-                                                                                        relationmap, 
-                                                                                        operator = operator, 
+                    cmdstring = self.build_command_string(leftcmd,
+                                                                                        relationmap,
+                                                                                        operator = operator,
                                                                                         cmd_type = "operator")
                     leftcmd = cmdstring
         # Add command list to result map.
         map_i.cmd_list = cmdstring
-        
+
         return(cmdstring)
-    
-    def set_temporal_extent_list(self, maplist, topolist = ["EQUAL"], temporal = 'l' , 
+
+    def set_temporal_extent_list(self, maplist, topolist = ["EQUAL"], temporal = 'l' ,
                                                         cmd_bool = False, cmd_type = None,  operator = None):
-        """ Change temporal extent of map list based on temporal relations to 
+        """ Change temporal extent of map list based on temporal relations to
                 other map list and given temporal operator.
 
-            :param maplist: List of map objects for which relations has been build 
+            :param maplist: List of map objects for which relations has been build
                                         correctely.
             :param topolist: List of strings of temporal relations.
             :param temporal: The temporal operator specifying the temporal
-                                            extent operation (intersection, union, disjoint 
+                                            extent operation (intersection, union, disjoint
                                             union, right reference, left reference).
             :param cmd_bool: Boolean if command string should be merged for related maps.
             :param cmd_type: map object with defined temporal relation to map_i:
@@ -388,26 +388,26 @@
             :return: Map list with specified temporal extent and optional command string.
         """
         resultdict = {}
-        
+
         for map_i in maplist:
             # Loop over temporal related maps and create overlay modules.
             tbrelations = map_i.get_temporal_relations()
             # Generate an intermediate map for the result map list.
-            map_new = self.generate_new_map(base_map=map_i, bool_op = 'and', 
+            map_new = self.generate_new_map(base_map=map_i, bool_op = 'and',
                                                                         copy = True,  rename = True)
-            
+
             # Combine temporal and spatial extents of intermediate map with related maps.
             for topo in topolist:
                 if topo in tbrelations.keys():
                     for map_j in (tbrelations[topo]):
                         if temporal == 'r':
                             # Generate an intermediate map for the result map list.
-                            map_new = self.generate_new_map(base_map=map_i, bool_op = 'and', 
+                            map_new = self.generate_new_map(base_map=map_i, bool_op = 'and',
                                                                                         copy = True,  rename = True)
                         # Create overlayed map extent.
                         returncode = self.overlay_map_extent(map_new, map_j, 'and', \
                                                                 temp_op = temporal)
-                        
+
                         # Stop the loop if no temporal or spatial relationship exist.
                         if returncode == 0:
                             break
@@ -417,9 +417,9 @@
                             # resultlist.append(map_new)
                             if cmd_bool:
                                 # Create r.mapcalc expression string for the operation.
-                                cmdstring = self.build_command_string(map_i,  
-                                                                                                    map_j, 
-                                                                                                    operator = operator, 
+                                cmdstring = self.build_command_string(map_i,
+                                                                                                    map_j,
+                                                                                                    operator = operator,
                                                                                                     cmd_type = cmd_type)
                                 # Conditional append of module command.
                                 map_new.cmd_list = cmdstring
@@ -433,12 +433,12 @@
         # Get sorted map objects as values from result dictionoary.
         resultlist = resultdict.values()
         resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
-        
+
         return(resultlist)
-    
-    def build_condition_cmd_list(self, iflist, thenlist,  elselist = None,  
-                                                        condition_topolist = ["EQUAL"], 
-                                                        conclusion_topolist = ["EQUAL"], 
+
+    def build_condition_cmd_list(self, iflist, thenlist,  elselist = None,
+                                                        condition_topolist = ["EQUAL"],
+                                                        conclusion_topolist = ["EQUAL"],
                                                         temporal = 'l', null = False):
         """This function build the r.mapcalc command strings for spatial conditionals.
             For Example: 'if(a1 == 1, b1, c2)'
@@ -446,52 +446,52 @@
             :param iflist: Map list with temporal extents and command list.
             :param thenlist: Map list with temporal extents and command list or numeric string.
             :param elselist: Map list with temporal extents and command list or numeric string.
-            :param condition_topolist: List of strings for given temporal relations between 
+            :param condition_topolist: List of strings for given temporal relations between
                             conditions and conclusions.
-            :param conclusion_topolist: List of strings for given temporal relations between 
+            :param conclusion_topolist: List of strings for given temporal relations between
                             conditions (then and else).
             :param temporal: The temporal operator specifying the temporal
-                                            extent operation (intersection, union, disjoint 
+                                            extent operation (intersection, union, disjoint
                                             union, right reference, left reference).
             :param null: Boolean if null map support should be activated.
 
             :return: map list with resulting command string for given condition type.
-        """    
+        """
         resultlist = []
         # First merge conclusion command maplists or strings.
         # Check if alternative conclusion map list is given.
         if all([isinstance(thenlist, list), isinstance(elselist, list)]):
             # Build conclusion command map list.
             conclusiontopolist = self.get_temporal_topo_list(thenlist, elselist,  conclusion_topolist)
-            conclusionlist = self.set_temporal_extent_list(conclusiontopolist, 
-                                                                                    topolist = conclusion_topolist, 
-                                                                                    temporal = temporal , 
-                                                                                    cmd_bool = True, 
+            conclusionlist = self.set_temporal_extent_list(conclusiontopolist,
+                                                                                    topolist = conclusion_topolist,
+                                                                                    temporal = temporal ,
+                                                                                    cmd_bool = True,
                                                                                     cmd_type = "conclusion")
         # Check if any conclusion is a numeric statements.
         elif any([isinstance(thenlist, str), isinstance(elselist, str)]):
-            conclusionlist = []            
+            conclusionlist = []
             # Check if only alternative conclusion is a numeric statements.
             if all([isinstance(thenlist, list), isinstance(elselist, str)]):
                 listinput = thenlist
                 numinput = elselist
                 for map_i in listinput:
                     # Create r.mapcalc expression string for the operation.
-                    cmdstring = self.build_command_string( map_i,  
-                                                                                            numinput, 
+                    cmdstring = self.build_command_string( map_i,
+                                                                                            numinput,
                                                                                             cmd_type = 'conclusion')
                     # Conditional append of module command.
                     map_i.cmd_list = cmdstring
                     # Append map to result map list.
                     conclusionlist.append(map_i)
             # Check if only direct conclusion is a numeric statements.
-            elif all([isinstance(thenlist, str), isinstance(elselist, list)]):                
+            elif all([isinstance(thenlist, str), isinstance(elselist, list)]):
                 listinput = elselist
                 numinput =  thenlist
                 for map_i in listinput:
                     # Create r.mapcalc expression string for the operation.
-                    cmdstring = self.build_command_string(numinput,  
-                                                                                            map_i,  
+                    cmdstring = self.build_command_string(numinput,
+                                                                                            map_i,
                                                                                             cmd_type = 'conclusion')
                     # Conditional append of module command.
                     map_i.cmd_list = cmdstring
@@ -502,14 +502,14 @@
         else:
             # The direct conclusion is used.
             conclusionlist = thenlist
-        # Use the conclusion map or string to merge it with the condition and 
+        # Use the conclusion map or string to merge it with the condition and
         # return maplist.
         if isinstance(conclusionlist,  str):
             resultlist = []
             for map_i in iflist:
                 # Create r.mapcalc expression string for the operation.
-                cmdstring = self.build_command_string(map_i,  
-                                                                                        conclusionlist,  
+                cmdstring = self.build_command_string(map_i,
+                                                                                        conclusionlist,
                                                                                         cmd_type = 'condition')
                 # Conditional append of module command.
                 map_i.cmd_list = cmdstring
@@ -518,12 +518,12 @@
             return(resultlist)
         elif isinstance(conclusionlist,  list):
             # Build result command map list between conditions and conclusions.
-            conditiontopolist = self.get_temporal_topo_list(iflist, conclusionlist,  
+            conditiontopolist = self.get_temporal_topo_list(iflist, conclusionlist,
                                                                                         topolist = condition_topolist)
-            resultlist = self.set_temporal_extent_list(conditiontopolist, 
-                                                                            topolist = condition_topolist, 
-                                                                            temporal = 'r' , 
-                                                                            cmd_bool = True, 
+            resultlist = self.set_temporal_extent_list(conditiontopolist,
+                                                                            topolist = condition_topolist,
+                                                                            temporal = 'r' ,
+                                                                            cmd_bool = True,
                                                                             cmd_type = "condition")
             return(resultlist)
 
@@ -570,21 +570,21 @@
                         m.inputs["expression"].value = str(m_expression)
                         m.flags["overwrite"].value = self.overwrite
                         process_queue.put(m)
-                    
+
                     elif map_i.map_exists():
                         # Copy map if it exists
                         map_test = map_i.get_new_instance(newident + "@" + self.mapset)
                         map_test.set_temporal_extent(map_i.get_temporal_extent())
                         map_test.set_spatial_extent(map_i.get_spatial_extent())
                         map_test_list.append(map_test)
-                        
+
                         m = copy.deepcopy(self.m_mapcalc)
                         m_expression = newident + "=" + map_i.get_map_id()
                         m.inputs["expression"].value = str(m_expression)
                         m.flags["overwrite"].value = self.overwrite
-                        print m.get_bash()
+                        print(m.get_bash())
                         process_queue.put(m)
-                        
+
                     else:
                         self.msgr.error(_("Error computing map <%s>"%(map_i.get_id()) ))
                     count  += 1
@@ -629,13 +629,13 @@
                 t[0] = register_list
 
                 self.remove_maps()
-    
+
     def p_expr_spmap_function(self, t):
         # Add a single map.
-        # Only the spatial extent of the map is evaluated. 
+        # Only the spatial extent of the map is evaluated.
         # Temporal extent is not existing.
         # Examples:
-        #    R = map(A) 
+        #    R = map(A)
         """
         mapexpr : MAP LPAREN stds RPAREN
         """
@@ -666,7 +666,7 @@
             t[0] = "map(" + t[3] + ")"
 
         if self.debug:
-            print "map(" + t[3] + ")"
+            print("map(" + t[3] + ")")
 
     def p_arith1_operation(self, t):
         """
@@ -692,7 +692,7 @@
         # Check input stds.
         maplistA = self.check_stds(t[1])
         maplistB = self.check_stds(t[3])
-        
+
         topolist = self.get_temporal_topo_list(maplistA, maplistB)
 
         if self.run:
@@ -718,8 +718,8 @@
                         name = self.generate_map_name()
 
                     # Create r.mapcalc expression string for the operation.
-                    cmdstring = self.build_command_string(map_i, map_j,  
-                                                                                    operator = t[2], 
+                    cmdstring = self.build_command_string(map_i, map_j,
+                                                                                    operator = t[2],
                                                                                     cmd_type = "operator")
                     # Conditional append of module command.
                     map_new.cmd_list = cmdstring
@@ -732,7 +732,7 @@
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
     def p_arith1_operation_numeric1(self, t):
         """
@@ -747,13 +747,13 @@
             | stds DIV numberstr
             | expr DIV numberstr
             | stds MULT numberstr
-            | expr MULT numberstr            
+            | expr MULT numberstr
             | stds MOD mapexpr
             | expr MOD mapexpr
             | stds DIV mapexpr
             | expr DIV mapexpr
             | stds MULT mapexpr
-            | expr MULT mapexpr            
+            | expr MULT mapexpr
         """
         # Check input stds.
         maplist = self.check_stds(t[1])
@@ -776,7 +776,7 @@
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
 
     def p_arith1_operation_numeric2(self, t):
@@ -792,13 +792,13 @@
             | numberstr DIV stds
             | numberstr DIV expr
             | numberstr MULT stds
-            | numberstr MULT expr            
+            | numberstr MULT expr
             | mapexpr MOD stds
             | mapexpr MOD expr
             | mapexpr DIV stds
             | mapexpr DIV expr
             | mapexpr MULT stds
-            | mapexpr MULT expr             
+            | mapexpr MULT expr
         """
         # Check input stds.
         maplist = self.check_stds(t[3])
@@ -821,7 +821,7 @@
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
 
     def p_arith2_operation(self, t):
@@ -867,10 +867,10 @@
                     else:
                         # Generate an intermediate map
                         name = self.generate_map_name()
-                    
+
                     # Create r.mapcalc expression string for the operation.
-                    cmdstring = self.build_command_string(map_i, map_j,  
-                                                                                    operator = t[2], 
+                    cmdstring = self.build_command_string(map_i, map_j,
+                                                                                    operator = t[2],
                                                                                     cmd_type = "operator")
                     # Conditional append of module command.
                     map_new.cmd_list = cmdstring
@@ -884,7 +884,7 @@
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
     def p_arith2_operation_numeric1(self, t):
         """
@@ -895,7 +895,7 @@
             | stds ADD numberstr
             | expr ADD numberstr
             | stds SUB numberstr
-            | expr SUB numberstr            
+            | expr SUB numberstr
             | stds ADD mapexpr
             | expr ADD mapexpr
             | stds SUB mapexpr
@@ -922,7 +922,7 @@
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
     def p_arith2_operation_numeric2(self, t):
         """
@@ -932,12 +932,12 @@
             | number SUB expr
             | numberstr ADD stds
             | numberstr ADD expr
-            | numberstr SUB stds            
-            | numberstr SUB expr     
+            | numberstr SUB stds
+            | numberstr SUB expr
             | mapexpr ADD stds
             | mapexpr ADD expr
             | mapexpr SUB stds
-            | mapexpr SUB expr   
+            | mapexpr SUB expr
         """
         # Check input stds.
         maplist = self.check_stds(t[3])
@@ -960,7 +960,7 @@
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
     def p_arith1_operation_relation(self, t):
         """
@@ -971,7 +971,7 @@
              | stds T_ARITH1_OPERATOR t_td_var
              | expr T_ARITH1_OPERATOR t_td_var
         """
-        if self.run:        
+        if self.run:
             # Check input stds.
             maplistA = self.check_stds(t[1])
             maplistB = self.check_stds(t[3])
@@ -980,14 +980,14 @@
             complist = self.get_temporal_topo_list(maplistA, maplistB, topolist = relations,
                                operator_cmd = True, compop = function)
             # Set temporal extent based on topological relationships.
-            resultlist = self.set_temporal_extent_list(complist, topolist = relations, 
+            resultlist = self.set_temporal_extent_list(complist, topolist = relations,
                                 temporal = temporal)
-        
-        t[0] = resultlist   
 
+        t[0] = resultlist
+
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
     def p_arith2_operation_relation(self, t):
         """
@@ -998,7 +998,7 @@
              | stds T_ARITH2_OPERATOR t_td_var
              | expr T_ARITH2_OPERATOR t_td_var
         """
-        if self.run:        
+        if self.run:
             # Check input stds.
             maplistA = self.check_stds(t[1])
             maplistB = self.check_stds(t[3])
@@ -1007,14 +1007,14 @@
             complist = self.get_temporal_topo_list(maplistA, maplistB, topolist = relations,
                                operator_cmd = True, compop = function)
             # Set temporal extent based on topological relationships.
-            resultlist = self.set_temporal_extent_list(complist, topolist = relations, 
+            resultlist = self.set_temporal_extent_list(complist, topolist = relations,
                                 temporal = temporal)
-        
+
         t[0] = resultlist
-  
+
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
     def p_arith_operation_numeric_string(self, t):
         """
@@ -1030,7 +1030,7 @@
 
         if self.debug:
             print(numstring)
-    
+
     def p_mapcalc_function(self, t):
         # Supported mapcalc functions.
         """
@@ -1051,7 +1051,7 @@
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
 
     def p_mapcalc_operation1(self, t):
@@ -1082,7 +1082,7 @@
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
     def p_mapexpr_operation(self, t):
         # Examples:
@@ -1099,7 +1099,7 @@
             t[0] = cmdstring
 
         if self.debug:
-            print mapstring
+            print(mapstring)
 
     def p_s_var_expr_1(self, t):
         # Examples:
@@ -1128,7 +1128,7 @@
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
     def p_s_var_expr_2(self, t):
         # Examples:
@@ -1157,7 +1157,7 @@
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
     def p_s_var_expr_3(self, t):
         # Examples:
@@ -1186,7 +1186,7 @@
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
     def p_s_var_expr_4(self, t):
         # Examples:
@@ -1215,8 +1215,8 @@
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
-    
+                print(map.cmd_list)
+
     def p_s_var_expr_comp(self, t):
         # Examples:
         #   A <= 2 || B == 10
@@ -1224,7 +1224,7 @@
         """
         s_var_expr : s_var_expr AND AND s_var_expr
                    | s_var_expr OR OR s_var_expr
-        """        
+        """
         if self.run:
             # Check input stds.
             s_var_exprA = self.check_stds(t[1])
@@ -1233,18 +1233,18 @@
             temporal = "l"
             function = t[2] + t[3]
             aggregate = t[2]
-            # Build conditional values based on topological relationships.            
+            # Build conditional values based on topological relationships.
             complist = self.get_temporal_topo_list(s_var_exprA, s_var_exprB, topolist = relations,
                                compare_cmd = True, compop = function, aggregate = aggregate)
             # Set temporal extent based on topological relationships.
-            resultlist = self.set_temporal_extent_list(complist, topolist = relations, 
+            resultlist = self.set_temporal_extent_list(complist, topolist = relations,
                                 temporal = temporal)
-                                
+
             t[0] = resultlist
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
     def p_s_var_expr_comp_op(self, t):
         # Examples:
@@ -1263,14 +1263,14 @@
             complist = self.get_temporal_topo_list(s_var_exprA, s_var_exprB, topolist = relations,
                                compare_cmd = True, compop = function, aggregate = aggregate)
             # Set temporal extent based on topological relationships.
-            resultlist = self.set_temporal_extent_list(complist, topolist = relations, 
+            resultlist = self.set_temporal_extent_list(complist, topolist = relations,
                                 temporal = temporal)
-            
+
             t[0] = resultlist
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
     def p_s_expr_condition_if(self, t):
         # Examples:
@@ -1284,16 +1284,16 @@
         """
         ifmaplist = self.check_stds(t[3])
         thenmaplist = self.check_stds(t[5])
-        resultlist = self.build_condition_cmd_list(ifmaplist, thenmaplist,  
-                                                                            elselist = None, 
-                                                                            condition_topolist = ["EQUAL"], 
-                                                                            conclusion_topolist = ["EQUAL"], 
+        resultlist = self.build_condition_cmd_list(ifmaplist, thenmaplist,
+                                                                            elselist = None,
+                                                                            condition_topolist = ["EQUAL"],
+                                                                            conclusion_topolist = ["EQUAL"],
                                                                             temporal = 'r', null = False)
         t[0] = resultlist
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
     def p_s_numeric_condition_if(self, t):
         # Examples:
@@ -1325,7 +1325,7 @@
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
     def p_s_expr_condition_if_relation(self, t):
         # Examples:
@@ -1336,20 +1336,20 @@
              | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds RPAREN
              | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr RPAREN
         """
-        relations, temporal, function,  aggregation = self.eval_toperator(t[3],  
+        relations, temporal, function,  aggregation = self.eval_toperator(t[3],
                                                                                         optype = 'relation')
         ifmaplist = self.check_stds(t[5])
         thenmaplist = self.check_stds(t[7])
-        resultlist = self.build_condition_cmd_list(ifmaplist, thenmaplist,  
-                                                                            elselist = None, 
-                                                                            condition_topolist = relations, 
-                                                                            conclusion_topolist = ["EQUAL"], 
+        resultlist = self.build_condition_cmd_list(ifmaplist, thenmaplist,
+                                                                            elselist = None,
+                                                                            condition_topolist = relations,
+                                                                            conclusion_topolist = ["EQUAL"],
                                                                             temporal = 'r', null = False)
         t[0] = resultlist
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
     def p_s_expr_condition_elif(self, t):
         # Examples:
@@ -1369,17 +1369,17 @@
         thenmaplist = self.check_stds(t[5])
         elsemaplist = self.check_stds(t[7])
         # Create conditional command map list.
-        resultlist = self.build_condition_cmd_list(ifmaplist, thenmaplist,  
-                                                                            elselist = elsemaplist, 
-                                                                            condition_topolist = ["EQUAL"], 
-                                                                            conclusion_topolist = ["EQUAL"], 
+        resultlist = self.build_condition_cmd_list(ifmaplist, thenmaplist,
+                                                                            elselist = elsemaplist,
+                                                                            condition_topolist = ["EQUAL"],
+                                                                            conclusion_topolist = ["EQUAL"],
                                                                             temporal = 'r', null = False)
 
         t[0] = resultlist
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
     def p_s_numeric_condition_elif(self, t):
         # Examples:
@@ -1393,7 +1393,7 @@
              | IF LPAREN ts_var_expr COMMA number COMMA number RPAREN
              | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN COMMA number RPAREN
              | IF LPAREN ts_var_expr COMMA number COMMA NULL LPAREN RPAREN RPAREN
-             | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN COMMA NULL LPAREN RPAREN RPAREN             
+             | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN COMMA NULL LPAREN RPAREN RPAREN
         """
         ifmaplist = self.check_stds(t[3])
         resultlist = []
@@ -1414,16 +1414,16 @@
         numelse = str(numelse)
         print(numthen + " " +numelse )
         # Create conditional command map list.
-        resultlist = self.build_condition_cmd_list(ifmaplist, numthen,  numelse,  
-                                                        condition_topolist = ["EQUAL"], 
-                                                        conclusion_topolist = ["EQUAL"], 
+        resultlist = self.build_condition_cmd_list(ifmaplist, numthen,  numelse,
+                                                        condition_topolist = ["EQUAL"],
+                                                        conclusion_topolist = ["EQUAL"],
                                                         temporal = 'r', null = False)
 
         t[0] = resultlist
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
     def p_s_numeric_expr_condition_elif(self, t):
         # Examples:
@@ -1445,7 +1445,7 @@
              | IF LPAREN ts_var_expr COMMA stds COMMA number RPAREN
              | IF LPAREN ts_var_expr COMMA stds COMMA NULL LPAREN RPAREN RPAREN
              | IF LPAREN ts_var_expr COMMA expr COMMA number RPAREN
-             | IF LPAREN ts_var_expr COMMA expr COMMA NULL LPAREN RPAREN RPAREN             
+             | IF LPAREN ts_var_expr COMMA expr COMMA NULL LPAREN RPAREN RPAREN
         """
         ifmaplist = self.check_stds(t[3])
         # Select input for r.mapcalc expression based on length of PLY object.
@@ -1465,16 +1465,16 @@
                 elseinput = str(t[7] + t[8] + t[9])
 
         # Create conditional command map list.
-        resultlist = self.build_condition_cmd_list(ifmaplist, theninput,  elseinput,  
-                                                        condition_topolist = ["EQUAL"], 
-                                                        conclusion_topolist = ["EQUAL"], 
+        resultlist = self.build_condition_cmd_list(ifmaplist, theninput,  elseinput,
+                                                        condition_topolist = ["EQUAL"],
+                                                        conclusion_topolist = ["EQUAL"],
                                                         temporal = 'r', null = False)
 
         t[0] = resultlist
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
     def p_s_numeric_expr_condition_elif_relation(self, t):
         # Examples:
@@ -1496,7 +1496,7 @@
              | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds COMMA number RPAREN
              | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds COMMA NULL LPAREN RPAREN RPAREN
              | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr COMMA number RPAREN
-             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr COMMA NULL LPAREN RPAREN RPAREN             
+             | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr COMMA NULL LPAREN RPAREN RPAREN
         """
         relations, temporal, function,  aggregation = self.eval_toperator(t[3],  optype = 'relation')
         ifmaplist = self.check_stds(t[5])
@@ -1517,16 +1517,16 @@
                 elseinput = str(t[9] + t[10] + t[11])
 
         # Create conditional command map list.
-        resultlist = self.build_condition_cmd_list(ifmaplist, theninput,  elseinput,  
-                                                        condition_topolist = relations, 
-                                                        conclusion_topolist = ["EQUAL"], 
+        resultlist = self.build_condition_cmd_list(ifmaplist, theninput,  elseinput,
+                                                        condition_topolist = relations,
+                                                        conclusion_topolist = ["EQUAL"],
                                                         temporal = 'r', null = False)
 
         t[0] = resultlist
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
 
     def p_s_expr_condition_elif_relation(self, t):
@@ -1546,18 +1546,18 @@
         ifmaplist = self.check_stds(t[5])
         thenmaplist = self.check_stds(t[7])
         elsemaplist = self.check_stds(t[9])
-        
+
         # Create conditional command map list.
-        resultlist = self.build_condition_cmd_list(ifmaplist, thenmaplist,  elsemaplist,  
-                                                        condition_topolist = relations, 
-                                                        conclusion_topolist = ["EQUAL"], 
+        resultlist = self.build_condition_cmd_list(ifmaplist, thenmaplist,  elsemaplist,
+                                                        condition_topolist = relations,
+                                                        conclusion_topolist = ["EQUAL"],
                                                         temporal = 'r', null = False)
 
         t[0] = resultlist
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
     def p_ts_var_expr1(self, t):
         # Combination of spatial and temporal conditional expressions.
@@ -1588,19 +1588,19 @@
             temporal = "l"
             function = t[2] + t[3]
             aggregate = t[2]
-            # Build conditional values based on topological relationships.            
-            complist = self.get_temporal_topo_list(s_var_exprA, s_var_exprB, 
-                                                                            topolist = relations, compare_cmd = True, 
-                                                                            compop = function, aggregate = aggregate,  
+            # Build conditional values based on topological relationships.
+            complist = self.get_temporal_topo_list(s_var_exprA, s_var_exprB,
+                                                                            topolist = relations, compare_cmd = True,
+                                                                            compop = function, aggregate = aggregate,
                                                                             convert = True)
             # Set temporal extent based on topological relationships.
-            resultlist = self.set_temporal_extent_list(complist, topolist = relations, 
+            resultlist = self.set_temporal_extent_list(complist, topolist = relations,
                                 temporal = temporal)
 
         t[0] = resultlist
-    
+
     def p_hash_operation(self, t):
-        # Calculate the number of maps within an interval of another map from a 
+        # Calculate the number of maps within an interval of another map from a
         # second space time dataset.
         # A # B
         # A {equal,r#} B
@@ -1628,7 +1628,7 @@
 
         if self.debug:
             for map in resultlist:
-                print map.cmd_list
+                print(map.cmd_list)
 
 ###############################################################################
 

Modified: grass/trunk/lib/python/temporal/temporal_topology_dataset_connector.py
===================================================================
--- grass/trunk/lib/python/temporal/temporal_topology_dataset_connector.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/temporal_topology_dataset_connector.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -16,6 +16,7 @@
 
 :authors: Soeren Gebbert
 """
+from __future__ import print_function
 import copy
 
 
@@ -104,7 +105,7 @@
             finished=a at P
             >>> rlist = tmr.get_temporal_relations()
             >>> if "FINISHED" in rlist.keys():
-            ...    print rlist["FINISHED"][0].get_id()
+            ...    print(rlist["FINISHED"][0].get_id())
             a at P
 
     """
@@ -503,85 +504,85 @@
     def print_temporal_topology_info(self):
         """Print information about this class in human readable style"""
 
-        print " +-------------------- Temporal Topology -------------------------------------+"
+        print(" +-------------------- Temporal Topology -------------------------------------+")
         #          0123456789012345678901234567890
         if self.next() is not None:
-            print " | Next: ...................... " + str(self.next().get_id())
+            print(" | Next: ...................... " + str(self.next().get_id()))
         if self.prev() is not None:
-            print " | Previous: .................. " + str(self.prev().get_id())
+            print(" | Previous: .................. " + str(self.prev().get_id()))
         if self.equal is not None:
-            print " | Equal:...................... " + \
-                self._generate_map_list_string(self.equal)
+            print(" | Equal:...................... " +
+                  self._generate_map_list_string(self.equal))
         if self.follows is not None:
-            print " | Follows: ................... " + \
-                self._generate_map_list_string(self.follows)
+            print(" | Follows: ................... " +
+                  self._generate_map_list_string(self.follows))
         if self.precedes is not None:
-            print " | Precedes: .................. " + \
-                self._generate_map_list_string(self.precedes)
+            print(" | Precedes: .................. " +
+                  self._generate_map_list_string(self.precedes))
         if self.overlaps is not None:
-            print " | Overlaps: .................. " + \
-                self._generate_map_list_string(self.overlaps)
+            print(" | Overlaps: .................. " +
+                  self._generate_map_list_string(self.overlaps))
         if self.overlapped is not None:
-            print " | Overlapped: ................ " + \
-                self._generate_map_list_string(self.overlapped)
+            print(" | Overlapped: ................ " +
+                  self._generate_map_list_string(self.overlapped))
         if self.during is not None:
-            print " | During: .................... " + \
-                self._generate_map_list_string(self.during)
+            print(" | During: .................... " +
+                  self._generate_map_list_string(self.during))
         if self.contains is not None:
-            print " | Contains: .................. " + \
-                self._generate_map_list_string(self.contains)
+            print(" | Contains: .................. " +
+                  self._generate_map_list_string(self.contains))
         if self.starts is not None:
-            print " | Starts:.. .................. " + \
-                self._generate_map_list_string(self.starts)
+            print(" | Starts:.. .................. " +
+                  self._generate_map_list_string(self.starts))
         if self.started is not None:
-            print " | Started:. .................. " + \
-                self._generate_map_list_string(self.started)
+            print(" | Started:. .................. " +
+                  self._generate_map_list_string(self.started))
         if self.finishes is not None:
-            print " | Finishes:................... " + \
-                self._generate_map_list_string(self.finishes)
+            print(" | Finishes:................... " +
+                  self._generate_map_list_string(self.finishes))
         if self.finished is not None:
-            print " | Finished:................... " + \
-                self._generate_map_list_string(self.finished)
+            print(" | Finished:................... " +
+                  self._generate_map_list_string(self.finished))
 
     def print_temporal_topology_shell_info(self):
         """Print information about this class in shell style"""
 
         if self.next() is not None:
-            print "next=" + self.next().get_id()
+            print("next=" + self.next().get_id())
         if self.prev() is not None:
-            print "prev=" + self.prev().get_id()
+            print("prev=" + self.prev().get_id())
         if self.equal is not None:
-            print "equal=" + self._generate_map_list_string(self.equal, False)
+            print("equal=" + self._generate_map_list_string(self.equal, False))
         if self.follows is not None:
-            print "follows=" + self._generate_map_list_string(self.follows,
-                                                              False)
+            print("follows=" + self._generate_map_list_string(self.follows,
+                                                              False))
         if self.precedes is not None:
-            print "precedes=" + self._generate_map_list_string(
-                self.precedes, False)
+            print("precedes=" + self._generate_map_list_string(
+                  self.precedes, False))
         if self.overlaps is not None:
-            print "overlaps=" + self._generate_map_list_string(
-                self.overlaps, False)
+            print("overlaps=" + self._generate_map_list_string(
+                  self.overlaps, False))
         if self.overlapped is not None:
-            print "overlapped=" + \
-                self._generate_map_list_string(self.overlapped, False)
+            print("overlapped=" +
+                  self._generate_map_list_string(self.overlapped, False))
         if self.during is not None:
-            print "during=" + self._generate_map_list_string(self.during,
-                                                             False)
+            print("during=" + self._generate_map_list_string(self.during,
+                                                             False))
         if self.contains is not None:
-            print "contains=" + self._generate_map_list_string(
-                self.contains, False)
+            print("contains=" + self._generate_map_list_string(
+                  self.contains, False))
         if self.starts is not None:
-            print "starts=" + \
-                self._generate_map_list_string(self.starts)
+            print("starts=" +
+                  self._generate_map_list_string(self.starts))
         if self.started is not None:
-            print "started=" + \
-                self._generate_map_list_string(self.started)
+            print("started=" +
+                  self._generate_map_list_string(self.started))
         if self.finishes is not None:
-            print "finishes=" + \
-                self._generate_map_list_string(self.finishes)
+            print("finishes=" +
+                  self._generate_map_list_string(self.finishes))
         if self.finished is not None:
-            print "finished=" + \
-                self._generate_map_list_string(self.finished)
+            print("finished=" +
+                  self._generate_map_list_string(self.finished))
 
 ###############################################################################
 

Modified: grass/trunk/lib/python/temporal/temporal_vector_algebra.py
===================================================================
--- grass/trunk/lib/python/temporal/temporal_vector_algebra.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/temporal_vector_algebra.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -41,10 +41,10 @@
     LexToken(RPAREN,')',1,16)
 
 """
-
+from __future__ import print_function
 import grass.pygrass.modules as pygrass
-from temporal_operator import *
-from temporal_algebra import *
+from .temporal_operator import *
+from .temporal_algebra import *
 
 ##############################################################################
 
@@ -129,7 +129,7 @@
         while True:
             tok = l.lexer.token()
             if not tok: break
-            
+
             if tok.type == "STVDS" or tok.type == "STRDS" or tok.type == "STR3DS":
                 raise SyntaxError("Syntax error near '%s'" %(tok.type))
 
@@ -149,12 +149,12 @@
     ######################### Temporal functions ##############################
 
     def get_temporal_topo_list(self, maplistA, maplistB = None, topolist = ["EQUAL"],
-                               assign_val = False, count_map = False, compare_bool = False,  
-                               compare_cmd = False,  compop = None, aggregate = None,  
+                               assign_val = False, count_map = False, compare_bool = False,
+                               compare_cmd = False,  compop = None, aggregate = None,
                                new = False,  convert = False,  overlay_cmd = False):
         """Build temporal topology for two space time data sets, copy map objects
           for given relation into map list.
-          
+
           :param maplistA: List of maps.
           :param maplistB: List of maps.
           :param topolist: List of strings of temporal relations.
@@ -170,11 +170,11 @@
           :param compop: Comparison operator, && or ||.
           :param aggregate: Aggregation operator for relation map list, & or |.
           :param new: Boolean if new temporary maps should be created.
-          :param convert: Boolean if conditional values should be converted to 
+          :param convert: Boolean if conditional values should be converted to
                         r.mapcalc command strings.
-          :param overlay_cmd: Boolean for aggregate overlay operators implicitly 
+          :param overlay_cmd: Boolean for aggregate overlay operators implicitly
                         in command list values based on related map lists.
-                    
+
           :return: List of maps from maplistA that fulfil the topological relationships
                   to maplistB specified in topolist.
         """
@@ -215,7 +215,7 @@
                 self.compare_cmd_value(map_i,  tbrelations, compop, aggregate, topolist, convert)
             elif overlay_cmd:
                 self.overlay_cmd_value(map_i,  tbrelations, compop, topolist)
-                
+
             for topo in topolist:
                 if topo.upper() in tbrelations.keys():
                     if count_map:
@@ -229,21 +229,21 @@
                     # Use unique identifier, since map names may be equal
                     resultdict[map_i.uid] = map_i
         resultlist = resultdict.values()
-        
+
         # Sort list of maps chronological.
         resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
-        
+
         return(resultlist)
 
     def overlay_cmd_value(self,  map_i, tbrelations, function, topolist = ["EQUAL"]):
         """ Function to evaluate two map lists by given overlay operator.
-        
+
           :param map_i: Map object with temporal extent.
           :param tbrelations: List of temporal relation to map_i.
           :param topolist: List of strings for given temporal relations.
           :param function: Overlay operator, &|+^~.
-          
-          :return: Map object with command list with  operators that has been 
+
+          :return: Map object with command list with  operators that has been
                         evaluated by implicit aggregration.
         """
         # Build comandlist list with elements from related maps and given relation operator.
@@ -292,30 +292,30 @@
                     mapainput = name
         # Add command list to result map.
         map_i.cmd_list = resultlist
-        
+
         return(resultlist)
 
     def set_temporal_extent_list(self, maplist, topolist = ["EQUAL"], temporal = 'l' ):
-        """ Change temporal extent of map list based on temporal relations to 
+        """ Change temporal extent of map list based on temporal relations to
                 other map list and given temporal operator.
 
-            :param maplist: List of map objects for which relations has been build 
+            :param maplist: List of map objects for which relations has been build
                                         correctely.
             :param topolist: List of strings of temporal relations.
             :param temporal: The temporal operator specifying the temporal
-                                            extent operation (intersection, union, disjoint 
+                                            extent operation (intersection, union, disjoint
                                             union, right reference, left reference).
 
             :return: Map list with specified temporal extent.
         """
         resultdict = {}
-        
+
         for map_i in maplist:
             # Loop over temporal related maps and create overlay modules.
             tbrelations = map_i.get_temporal_relations()
             # Generate an intermediate map for the result map list.
-            map_new = self.generate_new_map(base_map=map_i, bool_op = 'and', 
-                                                                        copy = True,  rename = False,  
+            map_new = self.generate_new_map(base_map=map_i, bool_op = 'and',
+                                                                        copy = True,  rename = False,
                                                                         remove = True)
             # Combine temporal and spatial extents of intermediate map with related maps.
             for topo in topolist:
@@ -323,8 +323,8 @@
                     for map_j in (tbrelations[topo]):
                         if temporal == 'r':
                             # Generate an intermediate map for the result map list.
-                            map_new = self.generate_new_map(base_map=map_i, bool_op = 'and', 
-                                                                                        copy = True,  rename = False,  
+                            map_new = self.generate_new_map(base_map=map_i, bool_op = 'and',
+                                                                                        copy = True,  rename = False,
                                                                                         remove = True)
                         # Create overlayed map extent.
                         returncode = self.overlay_map_extent(map_new, map_j, 'and', \
@@ -344,9 +344,9 @@
         # Get sorted map objects as values from result dictionoary.
         resultlist = resultdict.values()
         resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
-        
+
         return(resultlist)
-    
+
     ###########################################################################
 
     def p_statement_assign(self, t):
@@ -414,7 +414,7 @@
                                 break
                         if returncode == 0:
                             # We remove the invalid vector name from the remove list.
-                            if self.removable_maps.has_key(map_i.get_name()):
+                            if map_i.get_name() in self.removable_maps:
                                 self.removable_maps.pop(map_i.get_name())
                             mapset = map_i.get_mapset()
                             # Change map name to given basename.
@@ -427,7 +427,7 @@
                             count += 1
                             register_list.append(map_i)
                     else:
-                        # Test if temporal extents have been changed by temporal 
+                        # Test if temporal extents have been changed by temporal
                         # relation operators (i|r). This is a code copy from temporal_algebra.py
                         map_i_extent = map_i.get_temporal_extent_as_tuple()
                         map_test = map_i.get_new_instance(map_i.get_id())
@@ -483,11 +483,11 @@
                             # Map is original from an input STVDS
                             map_i.load()
                         # Register map in result space time dataset.
-                        print map_i.get_temporal_extent_as_tuple()
+                        print(map_i.get_temporal_extent_as_tuple())
                         success = resultstds.register_map(map_i, dbif=dbif)
                     resultstds.update_from_registered_maps(dbif)
-                
-            # Remove intermediate maps    
+
+            # Remove intermediate maps
             self.remove_maps()
             if connected:
                 dbif.close()
@@ -521,13 +521,13 @@
             maplistA = self.check_stds(t[1])
             maplistB = self.check_stds(t[3])
             relations = ["EQUAL"]
-            temporal = 'l' 
-            function = t[2] 
+            temporal = 'l'
+            function = t[2]
             # Build commmand list for related maps.
             complist = self.get_temporal_topo_list(maplistA, maplistB, topolist = relations,
                                                                     compop = function, overlay_cmd = True)
             # Set temporal extent based on topological relationships.
-            resultlist = self.set_temporal_extent_list(complist, topolist = relations, 
+            resultlist = self.set_temporal_extent_list(complist, topolist = relations,
                                 temporal = temporal)
 
             t[0] = resultlist
@@ -550,9 +550,9 @@
             complist = self.get_temporal_topo_list(maplistA, maplistB, topolist = relations,
                                                                     compop = function, overlay_cmd = True)
             # Set temporal extent based on topological relationships.
-            resultlist = self.set_temporal_extent_list(complist, topolist = relations, 
+            resultlist = self.set_temporal_extent_list(complist, topolist = relations,
                                 temporal = temporal)
-          
+
             t[0] = resultlist
         if self.debug:
             str(t[1]) + t[2] + str(t[3])

Modified: grass/trunk/lib/python/temporal/unit_tests.py
===================================================================
--- grass/trunk/lib/python/temporal/unit_tests.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/unit_tests.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -8,12 +8,14 @@
 
 :authors: Soeren Gebbert
 """
+from __future__ import print_function
+
 import copy
 from datetime import datetime
 import grass.script.core as core
-from temporal_granularity import *
-from datetime_math import *
-from space_time_datasets import *
+from .temporal_granularity import *
+from .datetime_math import *
+from .space_time_datasets import *
 
 import grass.lib.vector as vector
 import grass.lib.rtree as rtree
@@ -29,15 +31,15 @@
 def test_increment_datetime_by_string():
 
     # First test
-    print "# Test 1"
+    print("# Test 1")
     dt = datetime(2001, 9, 1, 0, 0, 0)
     string = "60 seconds, 4 minutes, 12 hours, 10 days, 1 weeks, 5 months, 1 years"
 
     dt1 = datetime(2003, 2, 18, 12, 5, 0)
     dt2 = increment_datetime_by_string(dt, string)
 
-    print dt
-    print dt2
+    print(dt)
+    print(dt2)
 
     delta = dt1 - dt2
 
@@ -45,15 +47,15 @@
         core.fatal("increment computation is wrong %s" % (delta))
 
     # Second test
-    print "# Test 2"
+    print("# Test 2")
     dt = datetime(2001, 11, 1, 0, 0, 0)
     string = "1 months"
 
     dt1 = datetime(2001, 12, 1)
     dt2 = increment_datetime_by_string(dt, string)
 
-    print dt
-    print dt2
+    print(dt)
+    print(dt2)
 
     delta = dt1 - dt2
 
@@ -61,15 +63,15 @@
         core.fatal("increment computation is wrong %s" % (delta))
 
     # Third test
-    print "# Test 3"
+    print("# Test 3")
     dt = datetime(2001, 11, 1, 0, 0, 0)
     string = "13 months"
 
     dt1 = datetime(2002, 12, 1)
     dt2 = increment_datetime_by_string(dt, string)
 
-    print dt
-    print dt2
+    print(dt)
+    print(dt2)
 
     delta = dt1 - dt2
 
@@ -77,15 +79,15 @@
         core.fatal("increment computation is wrong %s" % (delta))
 
     # 4. test
-    print "# Test 4"
+    print("# Test 4")
     dt = datetime(2001, 1, 1, 0, 0, 0)
     string = "72 months"
 
     dt1 = datetime(2007, 1, 1)
     dt2 = increment_datetime_by_string(dt, string)
 
-    print dt
-    print dt2
+    print(dt)
+    print(dt2)
 
     delta = dt1 - dt2
 
@@ -98,7 +100,7 @@
 def test_adjust_datetime_to_granularity():
 
     # First test
-    print "Test 1"
+    print("Test 1")
     dt = datetime(2001, 8, 8, 12, 30, 30)
     result = adjust_datetime_to_granularity(dt, "5 seconds")
     correct = datetime(2001, 8, 8, 12, 30, 30)
@@ -109,7 +111,7 @@
         core.fatal("Granularity adjustment computation is wrong %s" % (delta))
 
     # Second test
-    print "Test 2"
+    print("Test 2")
     result = adjust_datetime_to_granularity(dt, "20 minutes")
     correct = datetime(2001, 8, 8, 12, 30, 00)
 
@@ -119,7 +121,7 @@
         core.fatal("Granularity adjustment computation is wrong %s" % (delta))
 
     # Third test
-    print "Test 2"
+    print("Test 2")
     result = adjust_datetime_to_granularity(dt, "20 minutes")
     correct = datetime(2001, 8, 8, 12, 30, 00)
 
@@ -129,7 +131,7 @@
         core.fatal("Granularity adjustment computation is wrong %s" % (delta))
 
     # 4. test
-    print "Test 4"
+    print("Test 4")
     result = adjust_datetime_to_granularity(dt, "3 hours")
     correct = datetime(2001, 8, 8, 12, 00, 00)
 
@@ -139,7 +141,7 @@
         core.fatal("Granularity adjustment computation is wrong %s" % (delta))
 
     # 5. test
-    print "Test 5"
+    print("Test 5")
     result = adjust_datetime_to_granularity(dt, "5 days")
     correct = datetime(2001, 8, 8, 00, 00, 00)
 
@@ -149,7 +151,7 @@
         core.fatal("Granularity adjustment computation is wrong %s" % (delta))
 
     # 6. test
-    print "Test 6"
+    print("Test 6")
     result = adjust_datetime_to_granularity(dt, "2 weeks")
     correct = datetime(2001, 8, 6, 00, 00, 00)
 
@@ -159,7 +161,7 @@
         core.fatal("Granularity adjustment computation is wrong %s" % (delta))
 
     # 7. test
-    print "Test 7"
+    print("Test 7")
     result = adjust_datetime_to_granularity(dt, "6 months")
     correct = datetime(2001, 8, 1, 00, 00, 00)
 
@@ -169,7 +171,7 @@
         core.fatal("Granularity adjustment computation is wrong %s" % (delta))
 
     # 8. test
-    print "Test 8"
+    print("Test 8")
     result = adjust_datetime_to_granularity(dt, "2 years")
     correct = datetime(2001, 1, 1, 00, 00, 00)
 
@@ -179,7 +181,7 @@
         core.fatal("Granularity adjustment computation is wrong %s" % (delta))
 
     # 9. test
-    print "Test 9"
+    print("Test 9")
     result = adjust_datetime_to_granularity(
         dt, "2 years, 3 months, 5 days, 3 hours, 3 minutes, 2 seconds")
     correct = datetime(2001, 8, 8, 12, 30, 30)
@@ -190,7 +192,7 @@
         core.fatal("Granularity adjustment computation is wrong %s" % (delta))
 
     # 10. test
-    print "Test 10"
+    print("Test 10")
     result = adjust_datetime_to_granularity(dt, "3 months, 5 days, 3 minutes")
     correct = datetime(2001, 8, 8, 12, 30, 00)
 
@@ -200,7 +202,7 @@
         core.fatal("Granularity adjustment computation is wrong %s" % (delta))
 
     # 11. test
-    print "Test 11"
+    print("Test 11")
     result = adjust_datetime_to_granularity(dt, "3 weeks, 5 days")
     correct = datetime(2001, 8, 8, 00, 00, 00)
 
@@ -214,7 +216,7 @@
 
 def test_compute_datetime_delta():
 
-    print "Test 1"
+    print("Test 1")
     start = datetime(2001, 1, 1, 00, 00, 00)
     end = datetime(2001, 1, 1, 00, 00, 00)
 
@@ -228,7 +230,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 2"
+    print("Test 2")
     start = datetime(2001, 1, 1, 00, 00, 14)
     end = datetime(2001, 1, 1, 00, 00, 44)
 
@@ -242,7 +244,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 3"
+    print("Test 3")
     start = datetime(2001, 1, 1, 00, 00, 44)
     end = datetime(2001, 1, 1, 00, 01, 14)
 
@@ -256,7 +258,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 4"
+    print("Test 4")
     start = datetime(2001, 1, 1, 00, 00, 30)
     end = datetime(2001, 1, 1, 00, 05, 30)
 
@@ -270,7 +272,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 5"
+    print("Test 5")
     start = datetime(2001, 1, 1, 00, 00, 00)
     end = datetime(2001, 1, 1, 00, 01, 00)
 
@@ -284,7 +286,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 6"
+    print("Test 6")
     start = datetime(2011, 10, 31, 00, 45, 00)
     end = datetime(2011, 10, 31, 01, 45, 00)
 
@@ -298,7 +300,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 7"
+    print("Test 7")
     start = datetime(2011, 10, 31, 00, 45, 00)
     end = datetime(2011, 10, 31, 01, 15, 00)
 
@@ -312,7 +314,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 8"
+    print("Test 8")
     start = datetime(2011, 10, 31, 00, 45, 00)
     end = datetime(2011, 10, 31, 12, 15, 00)
 
@@ -326,7 +328,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 9"
+    print("Test 9")
     start = datetime(2011, 10, 31, 00, 00, 00)
     end = datetime(2011, 10, 31, 01, 00, 00)
 
@@ -340,7 +342,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 10"
+    print("Test 10")
     start = datetime(2011, 10, 31, 00, 00, 00)
     end = datetime(2011, 11, 01, 01, 00, 00)
 
@@ -354,7 +356,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 11"
+    print("Test 11")
     start = datetime(2011, 10, 31, 12, 00, 00)
     end = datetime(2011, 11, 01, 06, 00, 00)
 
@@ -368,7 +370,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 12"
+    print("Test 12")
     start = datetime(2011, 11, 01, 00, 00, 00)
     end = datetime(2011, 12, 01, 01, 00, 00)
 
@@ -382,7 +384,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 13"
+    print("Test 13")
     start = datetime(2011, 11, 01, 00, 00, 00)
     end = datetime(2011, 11, 05, 00, 00, 00)
 
@@ -396,7 +398,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 14"
+    print("Test 14")
     start = datetime(2011, 10, 06, 00, 00, 00)
     end = datetime(2011, 11, 05, 00, 00, 00)
 
@@ -410,7 +412,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 15"
+    print("Test 15")
     start = datetime(2011, 12, 02, 00, 00, 00)
     end = datetime(2012, 01, 01, 00, 00, 00)
 
@@ -424,7 +426,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 16"
+    print("Test 16")
     start = datetime(2011, 01, 01, 00, 00, 00)
     end = datetime(2011, 02, 01, 00, 00, 00)
 
@@ -438,7 +440,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 17"
+    print("Test 17")
     start = datetime(2011, 12, 01, 00, 00, 00)
     end = datetime(2012, 01, 01, 00, 00, 00)
 
@@ -452,7 +454,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 18"
+    print("Test 18")
     start = datetime(2011, 12, 01, 00, 00, 00)
     end = datetime(2012, 06, 01, 00, 00, 00)
 
@@ -466,7 +468,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 19"
+    print("Test 19")
     start = datetime(2011, 06, 01, 00, 00, 00)
     end = datetime(2021, 06, 01, 00, 00, 00)
 
@@ -480,7 +482,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 20"
+    print("Test 20")
     start = datetime(2011, 06, 01, 00, 00, 00)
     end = datetime(2012, 06, 01, 12, 00, 00)
 
@@ -495,7 +497,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 21"
+    print("Test 21")
     start = datetime(2011, 06, 01, 00, 00, 00)
     end = datetime(2012, 06, 01, 12, 30, 00)
 
@@ -510,7 +512,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 22"
+    print("Test 22")
     start = datetime(2011, 06, 01, 00, 00, 00)
     end = datetime(2012, 06, 01, 12, 00, 05)
 
@@ -525,7 +527,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 23"
+    print("Test 23")
     start = datetime(2011, 06, 01, 00, 00, 00)
     end = datetime(2012, 06, 01, 00, 30, 00)
 
@@ -540,7 +542,7 @@
     if delta != 0:
         core.fatal("Compute datetime delta is wrong %s" % (delta))
 
-    print "Test 24"
+    print("Test 24")
     start = datetime(2011, 06, 01, 00, 00, 00)
     end = datetime(2012, 06, 01, 00, 00, 05)
 
@@ -559,7 +561,7 @@
 def test_compute_absolute_time_granularity():
 
     # First we test intervals
-    print "Test 1"
+    print("Test 1")
     maps = []
     a = datetime(2001, 1, 1)
     increment = "1 year"
@@ -575,7 +577,7 @@
         core.fatal("Wrong granularity reference %s != gran %s" % (
             increment, gran))
 
-    print "Test 2"
+    print("Test 2")
     maps = []
     a = datetime(2001, 1, 1)
     increment = "3 years"
@@ -591,7 +593,7 @@
         core.fatal("Wrong granularity reference %s != gran %s" % (
             increment, gran))
 
-    print "Test 3"
+    print("Test 3")
     maps = []
     a = datetime(2001, 5, 1)
     increment = "1 month"
@@ -607,7 +609,7 @@
         core.fatal("Wrong granularity reference %s != gran %s" % (
             increment, gran))
 
-    print "Test 4"
+    print("Test 4")
     maps = []
     a = datetime(2001, 1, 1)
     increment = "3 months"
@@ -623,7 +625,7 @@
         core.fatal("Wrong granularity reference %s != gran %s" % (
             increment, gran))
 
-    print "Test 3"
+    print("Test 3")
     maps = []
     a = datetime(2001, 1, 1)
     increment = "1 day"
@@ -639,7 +641,7 @@
         core.fatal("Wrong granularity reference %s != gran %s" % (
             increment, gran))
 
-    print "Test 4"
+    print("Test 4")
     maps = []
     a = datetime(2001, 1, 14)
     increment = "14 days"
@@ -655,7 +657,7 @@
         core.fatal("Wrong granularity reference %s != gran %s" % (
             increment, gran))
 
-    print "Test 5"
+    print("Test 5")
     maps = []
     a = datetime(2001, 3, 1)
     increment = "1 month, 4 days"
@@ -672,7 +674,7 @@
         core.fatal("Wrong granularity reference %s != gran %s" % (
             increment, gran))
 
-    print "Test 6"
+    print("Test 6")
     maps = []
     a = datetime(2001, 2, 11)
     increment = "1 days, 1 hours"
@@ -689,7 +691,7 @@
         core.fatal("Wrong granularity reference %s != gran %s" % (
             increment, gran))
 
-    print "Test 7"
+    print("Test 7")
     maps = []
     a = datetime(2001, 6, 12)
     increment = "6 hours"
@@ -705,7 +707,7 @@
         core.fatal("Wrong granularity reference %s != gran %s" % (
             increment, gran))
 
-    print "Test 8"
+    print("Test 8")
     maps = []
     a = datetime(2001, 1, 1)
     increment = "20 minutes"
@@ -721,7 +723,7 @@
         core.fatal("Wrong granularity reference %s != gran %s" % (
             increment, gran))
 
-    print "Test 9"
+    print("Test 9")
     maps = []
     a = datetime(2001, 1, 1)
     increment = "5 hours, 25 minutes"
@@ -738,7 +740,7 @@
         core.fatal("Wrong granularity reference %s != gran %s" % (
             increment, gran))
 
-    print "Test 10"
+    print("Test 10")
     maps = []
     a = datetime(2001, 1, 1)
     increment = "5 minutes, 30 seconds"
@@ -755,7 +757,7 @@
         core.fatal("Wrong granularity reference %s != gran %s" % (
             increment, gran))
 
-    print "Test 11"
+    print("Test 11")
     maps = []
     a = datetime(2001, 12, 31)
     increment = "60 minutes, 30 seconds"
@@ -772,15 +774,15 @@
         core.fatal("Wrong granularity reference %s != gran %s" % (
             increment, gran))
 
-    print "Test 12"
+    print("Test 12")
     maps = []
     a = datetime(2001, 12, 31, 12, 30, 30)
     increment = "3600 seconds"
     for i in range(24):
         start = increment_datetime_by_string(a, increment, i)
         end = increment_datetime_by_string(a, increment, i + 1)
-        print start
-        print end
+        print(start)
+        print(end)
         map = RasterDataset(None)
         map.set_absolute_time(start, end)
         maps.append(map)
@@ -792,7 +794,7 @@
 
     # Test absolute time points
 
-    print "Test 13"
+    print("Test 13")
     maps = []
     a = datetime(2001, 12, 31, 12, 30, 30)
     increment = "3600 seconds"
@@ -808,7 +810,7 @@
         core.fatal("Wrong granularity reference %s != gran %s" % (
             increment, gran))
 
-    print "Test 14"
+    print("Test 14")
     maps = []
     a = datetime(2001, 12, 31, 00, 00, 00)
     increment = "20 days"
@@ -824,7 +826,7 @@
         core.fatal("Wrong granularity reference %s != gran %s" % (
             increment, gran))
 
-    print "Test 15"
+    print("Test 15")
     maps = []
     a = datetime(2001, 12, 01, 00, 00, 00)
     increment = "5 months"
@@ -842,7 +844,7 @@
 
     # Test absolute time interval and points
 
-    print "Test 16"
+    print("Test 16")
     maps = []
     a = datetime(2001, 12, 31, 12, 30, 30)
     increment = "3600 seconds"
@@ -867,7 +869,7 @@
         core.fatal("Wrong granularity reference %s != gran %s" % (
             increment, gran))
 
-    print "Test 17"
+    print("Test 17")
     maps = []
     a = datetime(2001, 1, 1)
     increment = "2 days"
@@ -970,7 +972,7 @@
     B.print_info()
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "equivalent":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -979,12 +981,12 @@
     B.print_info()
 
     relation = A.spatial_relation_2d(B)
-    print relation
+    print(relation)
     if relation != "cover":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "cover":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -993,22 +995,22 @@
     B.print_info()
 
     relation = A.spatial_relation_2d(B)
-    print relation
+    print(relation)
     if relation != "cover":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "cover":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
     relation = B.spatial_relation_2d(A)
-    print relation
+    print(relation)
     if relation != "covered":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
     relation = B.spatial_relation(A)
-    print relation
+    print(relation)
     if relation != "covered":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1017,17 +1019,17 @@
     B.print_info()
 
     relation = A.spatial_relation_2d(B)
-    print relation
+    print(relation)
     if relation != "cover":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
     relation = B.spatial_relation_2d(A)
-    print relation
+    print(relation)
     if relation != "covered":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "cover":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1035,7 +1037,7 @@
         north=70, south=30, east=50, west=20, bottom=-50, top=50)
 
     relation = B.spatial_relation(A)
-    print relation
+    print(relation)
     if relation != "covered":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1044,12 +1046,12 @@
     B.print_info()
 
     relation = A.spatial_relation_2d(B)
-    print relation
+    print(relation)
     if relation != "contain":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "cover":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1058,7 +1060,7 @@
     B.print_info()
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "cover":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1067,12 +1069,12 @@
     B.print_info()
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "contain":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
     relation = B.spatial_relation(A)
-    print relation
+    print(relation)
     if relation != "in":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1081,12 +1083,12 @@
     B.print_info()
 
     relation = A.spatial_relation_2d(B)
-    print relation
+    print(relation)
     if relation != "overlap":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "overlap":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1095,12 +1097,12 @@
     B.print_info()
 
     relation = A.spatial_relation_2d(B)
-    print relation
+    print(relation)
     if relation != "in":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "overlap":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1109,7 +1111,7 @@
     B.print_info()
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "overlap":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1118,7 +1120,7 @@
     B.print_info()
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "in":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1130,12 +1132,12 @@
     B.print_info()
 
     relation = A.spatial_relation_2d(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1147,12 +1149,12 @@
     B.print_info()
 
     relation = A.spatial_relation_2d(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1164,12 +1166,12 @@
     B.print_info()
 
     relation = A.spatial_relation_2d(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1181,12 +1183,12 @@
     B.print_info()
 
     relation = A.spatial_relation_2d(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1198,12 +1200,12 @@
     B.print_info()
 
     relation = A.spatial_relation_2d(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1215,12 +1217,12 @@
     B.print_info()
 
     relation = A.spatial_relation_2d(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1232,12 +1234,12 @@
     B.print_info()
 
     relation = A.spatial_relation_2d(B)
-    print relation
+    print(relation)
     if relation != "disjoint":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "disjoint":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1249,7 +1251,7 @@
     B.print_info()
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1261,7 +1263,7 @@
     B.print_info()
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1271,7 +1273,7 @@
     B.print_info()
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1281,7 +1283,7 @@
     B.print_info()
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1291,7 +1293,7 @@
     B.print_info()
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1301,7 +1303,7 @@
     B.print_info()
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1311,7 +1313,7 @@
     B.print_info()
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1321,7 +1323,7 @@
     B.print_info()
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1331,7 +1333,7 @@
     B.print_info()
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1341,7 +1343,7 @@
     B.print_info()
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1351,7 +1353,7 @@
     B.print_info()
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1361,7 +1363,7 @@
     B.print_info()
 
     relation = A.spatial_relation(B)
-    print relation
+    print(relation)
     if relation != "meet":
         core.fatal("Wrong spatial relation: %s" % (relation))
 
@@ -1392,7 +1394,7 @@
 
     count = 0
     for _map in tb:
-        print "[%s]" % (_map.get_name())
+        print("[%s]" % (_map.get_name()))
         _map.print_topology_info()
         if _map.get_id() != map_listA[count].get_id():
             core.fatal("Error building temporal topology <%s> != <%s>" %
@@ -1432,7 +1434,7 @@
 
     count = 0
     for _map in tb:
-        print "[%s]" % (_map.get_map_id())
+        print("[%s]" % (_map.get_map_id()))
         _map.print_topology_shell_info()
         if _map.get_id() != map_listB[count].get_id():
             core.fatal("Error building temporal topology <%s> != <%s>" %
@@ -1444,7 +1446,7 @@
 
     count = 0
     for _map in tb:
-        print "[%s]" % (_map.get_map_id())
+        print("[%s]" % (_map.get_map_id()))
         _map.print_topology_shell_info()
         if _map.get_id() != map_listA[count].get_id():
             core.fatal("Error building temporal topology <%s> != <%s>" %
@@ -1453,7 +1455,7 @@
 
     count = 0
     for _map in map_listB:
-        print "[%s]" % (_map.get_map_id())
+        print("[%s]" % (_map.get_map_id()))
         _map.print_topology_shell_info()
 
     # Probing some relations
@@ -1488,13 +1490,13 @@
     _map.set_absolute_time(datetime(2001, 03, 01), datetime(2001, 04, 01))
     map_list.append(copy.copy(_map))
 
-    print "Original"
+    print("Original")
     for _map in map_list:
-        print _map.get_temporal_extent_as_tuple()[0], _map.get_temporal_extent_as_tuple()[1]
-    print "Sorted by start time"
+        print(_map.get_temporal_extent_as_tuple()[0], _map.get_temporal_extent_as_tuple()[1])
+    print("Sorted by start time")
     new_list = sorted(map_list, key=AbstractDatasetComparisonKeyStartTime)
     for _map in new_list:
-        print _map.get_temporal_extent_as_tuple()[0], _map.get_temporal_extent_as_tuple()[1]
+        print(_map.get_temporal_extent_as_tuple()[0], _map.get_temporal_extent_as_tuple()[1])
 
     if new_list[0] != map_list[1]:
         core.fatal("Sorting by start time failed")
@@ -1503,10 +1505,10 @@
     if new_list[2] != map_list[2]:
         core.fatal("Sorting by start time failed")
 
-    print "Sorted by end time"
+    print("Sorted by end time")
     new_list = sorted(map_list, key=AbstractDatasetComparisonKeyEndTime)
     for _map in new_list:
-        print _map.get_temporal_extent_as_tuple()[0], _map.get_temporal_extent_as_tuple()[1]
+        print(_map.get_temporal_extent_as_tuple()[0], _map.get_temporal_extent_as_tuple()[1])
 
     if new_list[0] != map_list[1]:
         core.fatal("Sorting by end time failed")
@@ -1523,7 +1525,7 @@
 
     tree = rtree.RTreeCreateTree(-1, 0, 1)
 
-    for i in xrange(10):
+    for i in range(10):
 
         rect = rtree.RTreeAllocRect(tree)
         rtree.RTreeSetRect1D(rect, tree, float(i - 2), float(i + 2))
@@ -1539,9 +1541,9 @@
     rtree.RTreeFreeRect(rect)
 
     # print rectangle ids
-    print "Number of overlapping rectangles", num
-    for i in xrange(list_.n_values):
-        print "id", list_.value[i]
+    print("Number of overlapping rectangles", num)
+    for i in range(list_.n_values):
+        print("id", list_.value[i])
 
     rtree.RTreeDestroyTree(tree)
 
@@ -1553,7 +1555,7 @@
 
     tree = rtree.RTreeCreateTree(-1, 0, 2)
 
-    for i in xrange(10):
+    for i in range(10):
 
         rect = rtree.RTreeAllocRect(tree)
 
@@ -1571,9 +1573,9 @@
     rtree.RTreeFreeRect(rect)
 
     # print rectangle ids
-    print "Number of overlapping rectangles", num
-    for i in xrange(list_.n_values):
-        print "id", list_.value[i]
+    print("Number of overlapping rectangles", num)
+    for i in range(list_.n_values):
+        print("id", list_.value[i])
 
     rtree.RTreeDestroyTree(tree)
 
@@ -1585,7 +1587,7 @@
 
     tree = rtree.RTreeCreateTree(-1, 0, 3)
 
-    for i in xrange(10):
+    for i in range(10):
 
         rect = rtree.RTreeAllocRect(tree)
         rtree.RTreeSetRect3D(rect, tree,
@@ -1593,12 +1595,12 @@
                              float(i - 2), float(i + 2),
                              float(i - 2), float(i + 2))
         rtree.RTreeInsertRect(rect, i + 1, tree)
-        print i + 1
+        print(i + 1)
         rtree.RTreePrintRect(rect, 1, tree)
 
     rect = rtree.RTreeAllocRect(tree)
     rtree.RTreeSetRect3D(rect, tree, 2.0, 7.0, 2.0, 7.0, 2.0, 7.0)
-    print "Select"
+    print("Select")
     rtree.RTreePrintRect(rect, 1, tree)
 
     list_ = gis.ilist()
@@ -1607,9 +1609,9 @@
     rtree.RTreeFreeRect(rect)
 
     # print rectangle ids
-    print "Number of overlapping rectangles", num
-    for i in xrange(list_.n_values):
-        print "id", list_.value[i]
+    print("Number of overlapping rectangles", num)
+    for i in range(list_.n_values):
+        print("id", list_.value[i])
 
     rtree.RTreeDestroyTree(tree)
 
@@ -1621,7 +1623,7 @@
 
     tree = rtree.RTreeCreateTree(-1, 0, 4)
 
-    for i in xrange(10):
+    for i in range(10):
 
         # Allocate the boundary
         rect = rtree.RTreeAllocRect(tree)
@@ -1643,9 +1645,9 @@
     rtree.RTreeFreeRect(rect)
 
     # print rectangle ids
-    print "Number of overlapping rectangles", num
-    for i in xrange(list_.n_values):
-        print "id", list_.value[i]
+    print("Number of overlapping rectangles", num)
+    for i in range(list_.n_values):
+        print("id", list_.value[i])
 
     rtree.RTreeDestroyTree(tree)
 

Modified: grass/trunk/lib/python/temporal/univar_statistics.py
===================================================================
--- grass/trunk/lib/python/temporal/univar_statistics.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/lib/python/temporal/univar_statistics.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -18,8 +18,9 @@
 
 :authors: Soeren Gebbert
 """
+from __future__ import print_function
 
-from open_stds import *
+from .open_stds import *
 import grass.script as gscript
 
 ###############################################################################
@@ -71,7 +72,7 @@
             string += "third_quartile" + fs + "percentile_90"
 
         if output is None:
-            print string
+            print(string)
         else:
             out_file.write(string + "\n")
 
@@ -113,7 +114,7 @@
             string += fs + str(stats["third_quartile"]) + fs + str(stats["percentile_90"])
 
         if output is None:
-            print string
+            print(string)
         else:
             out_file.write(string + "\n")
 
@@ -191,7 +192,7 @@
                     "third_quartile" + fs + "percentile_90"
 
         if output is None:
-            print string
+            print(string)
         else:
             out_file.write(string + "\n")
 
@@ -254,7 +255,7 @@
                     string += fs + fs + fs + fs
 
         if output is None:
-            print string
+            print(string)
         else:
             out_file.write(string + "\n")
 

Modified: grass/trunk/scripts/d.correlate/d.correlate.py
===================================================================
--- grass/trunk/scripts/d.correlate/d.correlate.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/d.correlate/d.correlate.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -29,21 +29,23 @@
 import sys
 import os
 from grass.script.utils import try_remove
-from grass.script import core as grass
+from grass.script import core as gcore
 
+
 def main():
     layers = options['map'].split(',')
 
     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:
-	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'
 
@@ -52,53 +54,60 @@
     iloop = 0
     jloop = 0
     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
+        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')
-		grass.run_command('r.stats', flags = 'cnA', input = (i, j), stdout = ofile)
-		ofile.close()
+                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()
+                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)
+                kx = 100.0 / (maxx - minx + 1)
+                ky = 100.0 / (maxy - miny + 1)
 
-		p = grass.feed_command('d.graph', color = color)
-		ofile = p.stdin
+                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()
+                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()
+                ofile.close()
+                p.wait()
 
     try_remove(tmpfile)
 
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gcore.parser()
     main()

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

Modified: grass/trunk/scripts/d.polar/d.polar.py
===================================================================
--- grass/trunk/scripts/d.polar/d.polar.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/d.polar/d.polar.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -42,7 +42,6 @@
 #% description: Plot using Xgraph
 #%end
 
-import sys
 import os
 import string
 import types
@@ -51,16 +50,18 @@
 import glob
 import shutil
 from grass.script.utils import try_remove, basename
-from grass.script import core as grass
+from grass.script import core as gcore
 
+
 def cleanup():
     try_remove(tmp)
     for f in glob.glob(tmp + '_*'):
-	try_remove(f)
+        try_remove(f)
 
+
 def plot_xgraph():
     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:
         if isinstance(point, tuple):
             p.stdin.write("%f %f\n" % point)
@@ -69,16 +70,18 @@
     p.stdin.close()
     p.wait()
 
+
 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()
     frame_width = float(f[1])
     frame_height = float(f[2])
 
     # take shorter side as length of frame side
     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
 
     fl = dx
@@ -99,26 +102,27 @@
         for p in sine_cosine_replic if isinstance(p, tuple)]
 
     # 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
-    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:
     # 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!
     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",
         "width 0",
         "move 0 50",
@@ -126,16 +130,16 @@
         "move 50 0",
         "draw 50 100",
 
-	# draw the goods
+        # draw the goods
         "color red",
         "width 0",
         "polyline"] + sine_cosine_replic_normalized + [
-	# draw vector
+        # draw vector
         "color blue",
         "width 3",
         "polyline"] + vect + [
 
-	# draw compass text
+        # draw compass text
         "color black",
         "width 2",
         "size 10 10",
@@ -148,7 +152,7 @@
         "move 97 51",
         "text E",
 
-	# draw legend text
+        # draw legend text
         "width 0",
         "size 10",
         "color 0:180:0",
@@ -160,9 +164,9 @@
         "color blue",
         "move 0.5 90.5",
         "text Avg. direction"
-	]
+    ]
 
-    p = grass.feed_command('d.graph', env = tenv)
+    p = gcore.feed_command('d.graph', env=tenv)
     for point in lines:
         if isinstance(point, tuple):
             p.stdin.write("%f %f\n" % point)
@@ -171,9 +175,10 @@
     p.stdin.close()
     p.wait()
 
+
 def plot_eps(psout):
     # EPS output (by M.Neteler and Bruno Caprile, ITC-irst)
-    grass.message(_("Generating %s ...") % psout)
+    gcore.message(_("Generating %s ...") % psout)
 
     outerradius = maxradius
     epsscale = 0.1
@@ -188,10 +193,10 @@
     diagramfontsize = halfframe / 20
     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
     eastjustification = 6
@@ -200,12 +205,12 @@
 
     northxshift = 1.02 * halfframe
     northyshift = 1.98 * halfframe
-    eastxshift  = 1.98 * halfframe
-    eastyshift  = 1.02 * 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
+    westxshift = 0.01 * halfframe
+    westyshift = 1.02 * halfframe
 
     alldatastring = "all data (null included)"
     realdatastring = "real data angles"
@@ -219,7 +224,11 @@
     ##########
     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)
     shutil.copyfileobj(inf, outf)
     inf.close()
@@ -253,20 +262,24 @@
                                         %% first point moveto, then lineto
 """)
     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)
 
     sublength = len(outercircle) - 2
     (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:]:
-        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("""
 stroke
@@ -296,29 +309,33 @@
                                         %% first point moveto, then lineto
 """)
     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)
 
     sublength = len(sine_cosine_replic) - 2
     (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:]:
-        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("""
 stroke
@@ -333,14 +350,18 @@
                                         %% coordinates of rescaled, translated average direction follow
                                         %% first point moveto, second lineto
 """)
-    s = t.substitute(DIAGRAMLINEWIDTH = diagramlinewidth)
+    s = t.substitute(DIAGRAMLINEWIDTH=diagramlinewidth)
     outf.write(s)
 
     sublength = len(vector) - 2
     (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:]:
-        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("""
 stroke
@@ -362,20 +383,21 @@
 ($AVERAGEDIRECTIONSTRING) $LEGENDSX $AVERAGEDIRECTIONLEGENDY 4 just-string
 """)
     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.close()
 
-    grass.message(_("Done."))
+    gcore.message(_("Done."))
 
+
 def main():
     global tmp
     global sine_cosine_replic, outercircle, vector
@@ -386,31 +408,33 @@
     eps = options['output']
     xgraph = flags['x']
 
-    tmp = grass.tempfile()
+    tmp = gcore.tempfile()
 
     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:
     rawfile = tmp + "_raw"
     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 = file(rawfile)
     totalnumber = 0
     for line in rawf:
-	totalnumber += 1
+        totalnumber += 1
     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):
     # change 360 to 0 to close polar diagram:
     rawf = file(rawfile)
@@ -419,26 +443,26 @@
     sumsin = 0
     freq = {}
     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()
 
     totalvalidnumber = nvals
     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:
@@ -447,10 +471,8 @@
 
     #################################
     # how many are there?:
+    occurrences = sorted([(math.radians(x), freq[x]) for x in freq])
 
-    occurrences = [(math.radians(x), freq[x]) for x in freq]
-    occurrences.sort()
-
     # find the maximum value
     maxradius = max([f for a, f in occurrences])
 
@@ -460,14 +482,14 @@
     sine_cosine_replic = ['"Real data angles'] + sine_cosine + sine_cosine[0:1]
 
     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):
     vector = []
@@ -480,19 +502,28 @@
     # Now output:
 
     if eps:
-	psout = basename(eps, 'eps') + '.eps'
-	plot_eps(psout)
+        psout = basename(eps, 'eps') + '.eps'
+        plot_eps(psout)
     elif xgraph:
-	plot_xgraph()
+        plot_xgraph()
     else:
-	plot_dgraph()
+        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])))
+    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__":
-    options, flags = grass.parser()
+    options, flags = gcore.parser()
     atexit.register(cleanup)
     main()
-

Modified: grass/trunk/scripts/d.rast.edit/d.rast.edit.py
===================================================================
--- grass/trunk/scripts/d.rast.edit/d.rast.edit.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/d.rast.edit/d.rast.edit.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -16,7 +16,7 @@
 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 #  GNU General Public License for more details.
 #
-#############################################################################/
+# /
 
 #%module
 #% description: Edits cell values in a raster map.
@@ -81,15 +81,15 @@
 
 try:
     import wxversion
-    wxversion.select(['3.0', '2.8','2.6'])
+    wxversion.select(['3.0', '2.8', '2.6'])
     import wx
 except Exception:
     # ensure that --help, --interface-description etc work even without wx
     if __name__ == "__main__":
-	if len(sys.argv) == 2:
-	    arg = sys.argv[1]
-	    if arg[0:2] == '--' or arg in ["help", "-help"]:
-		grass.parser()
+        if len(sys.argv) == 2:
+            arg = sys.argv[1]
+            if arg[0:2] == '--' or arg in ["help", "-help"]:
+                grass.parser()
     # Either we didn't call g.parser, or it returned
     # At this point, there's nothing to be done except re-raise the exception
     raise
@@ -97,609 +97,637 @@
 wind_keys = {
     'north': ('n', float),
     'south': ('s', float),
-    'east':  ('e', float),
-    'west':  ('w', float),
+    'east': ('e', float),
+    'west': ('w', float),
     'nsres': ('nsres', float),
     'ewres': ('ewres', float),
-    'rows':  ('rows', int),
-    'cols':  ('cols', int),
-    }
+    'rows': ('rows', int),
+    'cols': ('cols', int),
+}
 
 gray12_bits = '\x00\x00\x22\x22\x00\x00\x88\x88\x00\x00\x22\x22\x00\x00\x88\x88\x00\x00\x22\x22\x00\x00\x88\x88\x00\x00\x22\x22\x00\x00\x88\x88'
 
+
 def run(cmd, **kwargs):
-    grass.run_command(cmd, quiet = True, **kwargs)
+    grass.run_command(cmd, quiet=True, **kwargs)
 
+
 class OverviewCanvas(wx.ScrolledWindow):
+
     def __init__(self, app, parent):
-	wx.ScrolledWindow.__init__(self, parent)
-	self.app = app
+        wx.ScrolledWindow.__init__(self, parent)
+        self.app = app
 
-	self.width = app.total['cols']
-	self.height = app.total['rows']
+        self.width = app.total['cols']
+        self.height = app.total['rows']
 
-	self.SetVirtualSize((self.width, self.height))
-	self.SetScrollRate(1, 1)
+        self.SetVirtualSize((self.width, self.height))
+        self.SetScrollRate(1, 1)
 
-	self.Bind(wx.EVT_LEFT_DOWN, self.OnMouse)
-	self.Bind(wx.EVT_MOTION, self.OnMouse)
-	self.Bind(wx.EVT_LEFT_UP, self.OnMouse)
-	self.Bind(wx.EVT_PAINT, self.OnPaint)
+        self.Bind(wx.EVT_LEFT_DOWN, self.OnMouse)
+        self.Bind(wx.EVT_MOTION, self.OnMouse)
+        self.Bind(wx.EVT_LEFT_UP, self.OnMouse)
+        self.Bind(wx.EVT_PAINT, self.OnPaint)
 
-	run('r.out.ppm', input = app.inmap, output = app.tempfile)
+        run('r.out.ppm', input=app.inmap, output=app.tempfile)
 
-	self.image = wx.BitmapFromImage(wx.Image(app.tempfile))
-	grass.try_remove(app.tempfile)
+        self.image = wx.BitmapFromImage(wx.Image(app.tempfile))
+        grass.try_remove(app.tempfile)
 
-	app.force_window()
+        app.force_window()
 
     def OnPaint(self, ev):
-	x0 = self.app.origin_x
-	y0 = self.app.origin_y
-	dx = self.app.cols
-	dy = self.app.rows
+        x0 = self.app.origin_x
+        y0 = self.app.origin_y
+        dx = self.app.cols
+        dy = self.app.rows
 
-	dc = wx.PaintDC(self)
-	self.DoPrepareDC(dc)
+        dc = wx.PaintDC(self)
+        self.DoPrepareDC(dc)
 
-	src = wx.MemoryDC()
-	src.SelectObjectAsSource(self.image)
-	dc.Blit(0, 0, self.width, self.height, src, 0, 0)
-	src.SelectObjectAsSource(wx.NullBitmap)
+        src = wx.MemoryDC()
+        src.SelectObjectAsSource(self.image)
+        dc.Blit(0, 0, self.width, self.height, src, 0, 0)
+        src.SelectObjectAsSource(wx.NullBitmap)
 
-	dc.SetPen(wx.Pen('red', style = wx.LONG_DASH))
-	dc.SetBrush(wx.Brush('black', style = wx.TRANSPARENT))
-	dc.DrawRectangle(x0, y0, dx, dy)
-	dc.SetBrush(wx.NullBrush)
-	dc.SetPen(wx.NullPen)
+        dc.SetPen(wx.Pen('red', style=wx.LONG_DASH))
+        dc.SetBrush(wx.Brush('black', style=wx.TRANSPARENT))
+        dc.DrawRectangle(x0, y0, dx, dy)
+        dc.SetBrush(wx.NullBrush)
+        dc.SetPen(wx.NullPen)
 
     def OnMouse(self, ev):
-	if ev.Moving():
-	    return
-	x = ev.GetX()
-	y = ev.GetY()
-	(x, y) = self.CalcUnscrolledPosition(x, y)
-	self.set_window(x, y)
-	if ev.ButtonUp():
-	    self.app.change_window()
+        if ev.Moving():
+            return
+        x = ev.GetX()
+        y = ev.GetY()
+        (x, y) = self.CalcUnscrolledPosition(x, y)
+        self.set_window(x, y)
+        if ev.ButtonUp():
+            self.app.change_window()
 
     def set_window(self, x, y):
-	self.app.origin_x = x - app.cols / 2
-	self.app.origin_y = y - app.rows / 2
-	self.app.force_window()
-	self.Refresh()
+        self.app.origin_x = x - app.cols / 2
+        self.app.origin_y = y - app.rows / 2
+        self.app.force_window()
+        self.Refresh()
 
+
 class OverviewWindow(wx.Frame):
+
     def __init__(self, app):
-	wx.Frame.__init__(self, None, title = "d.rast.edit overview (%s)" % app.inmap)
-	self.app = app
+        wx.Frame.__init__(
+            self,
+            None,
+            title="d.rast.edit overview (%s)" %
+            app.inmap)
+        self.app = app
 
-	self.canvas = OverviewCanvas(app, parent = self)
+        self.canvas = OverviewCanvas(app, parent=self)
 
-	self.Bind(wx.EVT_CLOSE, self.OnClose)
+        self.Bind(wx.EVT_CLOSE, self.OnClose)
 
     def OnClose(self, ev):
-	self.app.finalize()
+        self.app.finalize()
 
+
 class Canvas(wx.ScrolledWindow):
+
     def __init__(self, app, parent):
-	wx.ScrolledWindow.__init__(self, parent)
-	self.app = app
+        wx.ScrolledWindow.__init__(self, parent)
+        self.app = app
 
-	self.size = app.size
+        self.size = app.size
 
-	w = app.cols * self.size
-	h = app.rows * self.size
+        w = app.cols * self.size
+        h = app.rows * self.size
 
-	self.SetVirtualSize((w, h))
-	self.SetVirtualSizeHints(50, 50)
-	self.SetScrollRate(1, 1)
+        self.SetVirtualSize((w, h))
+        self.SetVirtualSizeHints(50, 50)
+        self.SetScrollRate(1, 1)
 
-	self.Bind(wx.EVT_LEFT_DOWN, self.OnMouse)
-	self.Bind(wx.EVT_RIGHT_DOWN, self.OnMouse)
-	self.Bind(wx.EVT_MOTION, self.OnMouse)
-	self.Bind(wx.EVT_PAINT, self.OnPaint2)
+        self.Bind(wx.EVT_LEFT_DOWN, self.OnMouse)
+        self.Bind(wx.EVT_RIGHT_DOWN, self.OnMouse)
+        self.Bind(wx.EVT_MOTION, self.OnMouse)
+        self.Bind(wx.EVT_PAINT, self.OnPaint2)
 
-	self.row = 0
-	self.col = 0
+        self.row = 0
+        self.col = 0
 
-	self.gray12 = wx.BitmapFromBits(gray12_bits, 16, 16)
+        self.gray12 = wx.BitmapFromBits(gray12_bits, 16, 16)
 
     def OnMouse(self, ev):
-	oldrow = self.row
-	oldcol = self.col
+        oldrow = self.row
+        oldcol = self.col
 
-	x = ev.GetX()
-	y = ev.GetY()
-	(x, y) = self.CalcUnscrolledPosition(x, y)
+        x = ev.GetX()
+        y = ev.GetY()
+        (x, y) = self.CalcUnscrolledPosition(x, y)
 
-	col = x / self.size
-	row = y / self.size
+        col = x / self.size
+        row = y / self.size
 
-	self.row = row
-	self.col = col
+        self.row = row
+        self.col = col
 
-	if ev.Moving():
-	    self.refresh_cell(oldrow, oldcol)
-	    self.refresh_cell(row, col)
-	elif ev.ButtonDown(wx.MOUSE_BTN_LEFT):
-	    self.cell_set()
-	elif ev.ButtonDown(wx.MOUSE_BTN_RIGHT):
-	    self.cell_get()
+        if ev.Moving():
+            self.refresh_cell(oldrow, oldcol)
+            self.refresh_cell(row, col)
+        elif ev.ButtonDown(wx.MOUSE_BTN_LEFT):
+            self.cell_set()
+        elif ev.ButtonDown(wx.MOUSE_BTN_RIGHT):
+            self.cell_get()
 
     def paint_cell(self, dc, r, c):
-	if r < 0 or r >= self.app.rows or c < 0 or c >= self.app.cols:
-	    return
+        if r < 0 or r >= self.app.rows or c < 0 or c >= self.app.cols:
+            return
 
-	val = self.app.values[r][c]
-	if val == None:
-	    fill = 'black'
-	    stipple = self.gray12 
-	else:
-	    fill = self.app.get_color(val)
-	    stipple = None
+        val = self.app.values[r][c]
+        if val is None:
+            fill = 'black'
+            stipple = self.gray12
+        else:
+            fill = self.app.get_color(val)
+            stipple = None
 
-	if r == self.row and c == self.col:
-	    outline = 'red'
-	elif self.app.changed[r][c]:
-	    outline = 'white'
-	else:
-	    outline = 'black'
+        if r == self.row and c == self.col:
+            outline = 'red'
+        elif self.app.changed[r][c]:
+            outline = 'white'
+        else:
+            outline = 'black'
 
-	dc.SetPen(wx.Pen(outline))
+        dc.SetPen(wx.Pen(outline))
 
-	if stipple:
-	    brush = wx.Brush(fill, style = wx.STIPPLE)
-	    brush.SetStipple(stipple)
-	else:
-	    brush = wx.Brush(fill, style = wx.SOLID)
+        if stipple:
+            brush = wx.Brush(fill, style=wx.STIPPLE)
+            brush.SetStipple(stipple)
+        else:
+            brush = wx.Brush(fill, style=wx.SOLID)
 
-	x0 = c * self.size + 1
-	x1 = x0  + self.size - 1
-	y0 = r * self.size + 1
-	y1 = y0  + self.size - 1
+        x0 = c * self.size + 1
+        x1 = x0 + self.size - 1
+        y0 = r * self.size + 1
+        y1 = y0 + self.size - 1
 
-	dc.SetBrush(brush)
-	dc.DrawRectangle(x0, y0, x1 - x0, y1 - y0)
-	dc.SetPen(wx.NullPen)
-	dc.SetBrush(wx.NullBrush)
+        dc.SetBrush(brush)
+        dc.DrawRectangle(x0, y0, x1 - x0, y1 - y0)
+        dc.SetPen(wx.NullPen)
+        dc.SetBrush(wx.NullBrush)
 
-	if not self.app.angles:
-	    return
+        if not self.app.angles:
+            return
 
-	if self.app.angles[r][c] == '*':
-	    return
+        if self.app.angles[r][c] == '*':
+            return
 
-	cx = (x0 + x1) / 2
-	cy = (y0 + y1) / 2
+        cx = (x0 + x1) / 2
+        cy = (y0 + y1) / 2
 
-	a = math.radians(float(self.app.angles[r][c]))
-	dx =  math.cos(a) * self.size / 2
-	dy = -math.sin(a) * self.size / 2
+        a = math.radians(float(self.app.angles[r][c]))
+        dx = math.cos(a) * self.size / 2
+        dy = -math.sin(a) * self.size / 2
 
-	x0 = cx - dx
-	y0 = cy - dy
-	x1 = cx + dx
-	y1 = cy + dy
+        x0 = cx - dx
+        y0 = cy - dy
+        x1 = cx + dx
+        y1 = cy + dy
 
-	dx, dy = x1 - x0, y1 - y0
-	px, py = -dy, dx
+        dx, dy = x1 - x0, y1 - y0
+        px, py = -dy, dx
 
-	r,g,b = wx.NamedColor(fill)
-	if r + g + b > 384:
-	    line = 'black'
-	else:
-	    line = 'white'
+        r, g, b = wx.NamedColor(fill)
+        if r + g + b > 384:
+            line = 'black'
+        else:
+            line = 'white'
 
-	dc.SetPen(wx.Pen(line))
-	dc.DrawLine(x0, y0, x1, y1)
-	dc.DrawLine(x1, y1, x1 + px/6 - dx/3, y1 + py/6 - dy/3)
-	dc.DrawLine(x1, y1, x1 - px/6 - dx/3, y1 - py/6 - dy/3)
-	dc.SetPen(wx.NullPen)
+        dc.SetPen(wx.Pen(line))
+        dc.DrawLine(x0, y0, x1, y1)
+        dc.DrawLine(x1, y1, x1 + px / 6 - dx / 3, y1 + py / 6 - dy / 3)
+        dc.DrawLine(x1, y1, x1 - px / 6 - dx / 3, y1 - py / 6 - dy / 3)
+        dc.SetPen(wx.NullPen)
 
     def paint_rect(self, dc, x, y, w, h):
-	c0 = (x + 0) / self.size
-	c1 = (x + w + 1) / self.size
-	r0 = (y + 0) / self.size
-	r1 = (y + h + 1) / self.size
-	for r in range(r0, r1 + 1):
-	    for c in range(c0, c1 + 1):
-		self.paint_cell(dc, r, c)
+        c0 = (x + 0) / self.size
+        c1 = (x + w + 1) / self.size
+        r0 = (y + 0) / self.size
+        r1 = (y + h + 1) / self.size
+        for r in range(r0, r1 + 1):
+            for c in range(c0, c1 + 1):
+                self.paint_cell(dc, r, c)
 
     def OnPaint(self, ev):
-	dc = wx.PaintDC(self)
-	self.DoPrepareDC(dc)
-	for r in range(self.app.rows):
-	    for c in range(self.app.cols):
-		self.paint_cell(dc, r, c)
+        dc = wx.PaintDC(self)
+        self.DoPrepareDC(dc)
+        for r in range(self.app.rows):
+            for c in range(self.app.cols):
+                self.paint_cell(dc, r, c)
 
     def OnPaint2(self, ev):
-	dc = wx.PaintDC(self)
-	self.DoPrepareDC(dc)
-	it = wx.RegionIterator(self.GetUpdateRegion())
-	while it.HaveRects():
-	    x = it.GetX()
-	    y = it.GetY()
-	    w = it.GetW()
-	    h = it.GetH()
-	    (x, y) = self.CalcUnscrolledPosition(x, y)
-	    self.paint_rect(dc, x, y, w, h)
-	    it.Next()
+        dc = wx.PaintDC(self)
+        self.DoPrepareDC(dc)
+        it = wx.RegionIterator(self.GetUpdateRegion())
+        while it.HaveRects():
+            x = it.GetX()
+            y = it.GetY()
+            w = it.GetW()
+            h = it.GetH()
+            (x, y) = self.CalcUnscrolledPosition(x, y)
+            self.paint_rect(dc, x, y, w, h)
+            it.Next()
 
     def cell_enter(self):
-	if not self.row or not self.col:
-	    return
-	self.app.update_status(self.row, self.col)
+        if not self.row or not self.col:
+            return
+        self.app.update_status(self.row, self.col)
 
     def cell_leave(self):
-	self.app.clear_status()
+        self.app.clear_status()
 
     def cell_get(self):
-	self.app.brush = self.app.values[self.row][self.col]
-	self.app.frame.brush_update()
+        self.app.brush = self.app.values[self.row][self.col]
+        self.app.frame.brush_update()
 
     def cell_set(self):
-	self.app.values[self.row][self.col] = self.app.brush
-	self.app.changed[self.row][self.col] = True
-	self.refresh_cell(self.row, self.col)
+        self.app.values[self.row][self.col] = self.app.brush
+        self.app.changed[self.row][self.col] = True
+        self.refresh_cell(self.row, self.col)
 
     def refresh_cell(self, row, col):
-	x = col * self.size
-	y = row * self.size
-	(x, y) = self.CalcScrolledPosition(x, y)
-	self.RefreshRect((x, y, self.size, self.size))
+        x = col * self.size
+        y = row * self.size
+        (x, y) = self.CalcScrolledPosition(x, y)
+        self.RefreshRect((x, y, self.size, self.size))
 
+
 class ColorPanel(wx.Panel):
+
     def __init__(self, **kwargs):
-	wx.Panel.__init__(self, **kwargs)
-	self.SetBackgroundStyle(wx.BG_STYLE_COLOUR)
-	self.stipple = wx.BitmapFromBits(gray12_bits, 16, 16)
-	self.null_bg = True
-	self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnErase)
+        wx.Panel.__init__(self, **kwargs)
+        self.SetBackgroundStyle(wx.BG_STYLE_COLOUR)
+        self.stipple = wx.BitmapFromBits(gray12_bits, 16, 16)
+        self.null_bg = True
+        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnErase)
 
     def OnErase(self, ev):
-	self.ClearBackground()
+        self.ClearBackground()
 
-	if not self.null_bg:
-	    return
+        if not self.null_bg:
+            return
 
-	dc = ev.GetDC()
-	if not dc:
-	    dc = wx.ClientDC(self)
+        dc = ev.GetDC()
+        if not dc:
+            dc = wx.ClientDC(self)
 
-	brush = wx.Brush('black', style = wx.STIPPLE)
-	brush.SetStipple(self.stipple)
-	dc.SetBackground(brush)
-	dc.Clear()
-	dc.SetBackground(wx.NullBrush)
+        brush = wx.Brush('black', style=wx.STIPPLE)
+        brush.SetStipple(self.stipple)
+        dc.SetBackground(brush)
+        dc.Clear()
+        dc.SetBackground(wx.NullBrush)
 
     def SetNullBackgroundColour(self):
-	wx.Panel.SetBackgroundColour(self, 'gray')
-	self.null_bg = True
+        wx.Panel.SetBackgroundColour(self, 'gray')
+        self.null_bg = True
 
     def SetBackgroundColour(self, color):
-	wx.Panel.SetBackgroundColour(self, color)
-	self.null_bg = False
+        wx.Panel.SetBackgroundColour(self, color)
+        self.null_bg = False
 
+
 class MainWindow(wx.Frame):
+
     def __init__(self, app):
-	wx.Frame.__init__(self, None, title = "d.rast.edit (%s)" % app.inmap)
-	self.app = app
+        wx.Frame.__init__(self, None, title="d.rast.edit (%s)" % app.inmap)
+        self.app = app
 
-	self.Bind(wx.EVT_CLOSE, self.OnClose)
+        self.Bind(wx.EVT_CLOSE, self.OnClose)
 
-	filemenu = wx.Menu()
-	filemenu.Append(wx.ID_SAVE, "&Save", "Save changes")
-	filemenu.Append(wx.ID_EXIT, "E&xit", "Terminate the program")
-	menubar = wx.MenuBar()
-	menubar.Append(filemenu, "&File")
-	self.SetMenuBar(menubar)
+        filemenu = wx.Menu()
+        filemenu.Append(wx.ID_SAVE, "&Save", "Save changes")
+        filemenu.Append(wx.ID_EXIT, "E&xit", "Terminate the program")
+        menubar = wx.MenuBar()
+        menubar.Append(filemenu, "&File")
+        self.SetMenuBar(menubar)
 
-	wx.EVT_MENU(self, wx.ID_SAVE, self.OnSave)
-	wx.EVT_MENU(self, wx.ID_EXIT, self.OnExit)
+        wx.EVT_MENU(self, wx.ID_SAVE, self.OnSave)
+        wx.EVT_MENU(self, wx.ID_EXIT, self.OnExit)
 
-	sizer = wx.BoxSizer(orient = wx.VERTICAL)
+        sizer = wx.BoxSizer(orient=wx.VERTICAL)
 
-	self.canvas = Canvas(app, parent = self)
-	si = sizer.Add(self.canvas, proportion = 1, flag = wx.EXPAND)
+        self.canvas = Canvas(app, parent=self)
+        si = sizer.Add(self.canvas, proportion=1, flag=wx.EXPAND)
 
-	tools = wx.BoxSizer(wx.HORIZONTAL)
+        tools = wx.BoxSizer(wx.HORIZONTAL)
 
-	l = wx.StaticText(parent = self, label = 'New Value:')
-	tools.Add(l, flag = wx.ALIGN_CENTER_VERTICAL)
-	tools.AddSpacer(5)
+        l = wx.StaticText(parent=self, label='New Value:')
+        tools.Add(l, flag=wx.ALIGN_CENTER_VERTICAL)
+        tools.AddSpacer(5)
 
-	self.newval = wx.TextCtrl(parent = self, style = wx.TE_PROCESS_ENTER)
-	tools.Add(self.newval, flag = wx.ALIGN_CENTER_VERTICAL)
+        self.newval = wx.TextCtrl(parent=self, style=wx.TE_PROCESS_ENTER)
+        tools.Add(self.newval, flag=wx.ALIGN_CENTER_VERTICAL)
 
-	l = wx.StaticText(parent = self, label = 'Color:')
-	tools.Add(l, flag = wx.ALIGN_CENTER_VERTICAL)
-	tools.AddSpacer(5)
+        l = wx.StaticText(parent=self, label='Color:')
+        tools.Add(l, flag=wx.ALIGN_CENTER_VERTICAL)
+        tools.AddSpacer(5)
 
-	self.color = ColorPanel(parent = self, size = (30,5))
-	tools.Add(self.color, flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
+        self.color = ColorPanel(parent=self, size=(30, 5))
+        tools.Add(self.color, flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
 
-	self.Bind(wx.EVT_TEXT_ENTER, self.OnReturn, source = self.newval)
+        self.Bind(wx.EVT_TEXT_ENTER, self.OnReturn, source=self.newval)
 
-	sizer.AddSizer(tools, proportion = 0, flag = wx.EXPAND)
+        sizer.AddSizer(tools, proportion=0, flag=wx.EXPAND)
 
-	self.SetSizerAndFit(sizer)
-	self.SetSize((app.width, app.height))
+        self.SetSizerAndFit(sizer)
+        self.SetSize((app.width, app.height))
 
-	self.status = self.CreateStatusBar(6)
+        self.status = self.CreateStatusBar(6)
 
-	self.brush_update()
+        self.brush_update()
 
     def OnSave(self, ev):
-	self.app.save_map()
+        self.app.save_map()
 
     def OnExit(self, ev):
-	self.Close(True)
+        self.Close(True)
 
     def OnClose(self, ev):
-	self.app.finalize()
+        self.app.finalize()
 
     def OnReturn(self, ev):
-	self.app.brush = self.newval.GetValue()
-	if self.app.brush != '*' and self.app.brush.strip('0123456789') != '':
-	    self.app.brush = '*'
-	self.brush_update()
+        self.app.brush = self.newval.GetValue()
+        if self.app.brush != '*' and self.app.brush.strip('0123456789') != '':
+            self.app.brush = '*'
+        self.brush_update()
 
     def update_status(self):
-	for i, key in enumerate(['row', 'col', 'x', 'y', 'value', 'aspect']):
-	    s = "%s%s: %s" % (key[0].upper(), key[1:], self.app.status[key])
-	    self.status.SetStatusText(s, i)
+        for i, key in enumerate(['row', 'col', 'x', 'y', 'value', 'aspect']):
+            s = "%s%s: %s" % (key[0].upper(), key[1:], self.app.status[key])
+            self.status.SetStatusText(s, i)
 
     def clear_status(self):
-	for key in self.status:
-	    self.status[key] = ''
+        for key in self.status:
+            self.status[key] = ''
 
     def brush_update(self):
-	self.newval.ChangeValue(self.app.brush)
-	if self.app.brush == '*':
-	    self.color.SetNullBackgroundColour()
-	else:
-	    self.color.SetBackgroundColour(self.app.get_color(self.app.brush))
-	self.color.Refresh()
+        self.newval.ChangeValue(self.app.brush)
+        if self.app.brush == '*':
+            self.color.SetNullBackgroundColour()
+        else:
+            self.color.SetBackgroundColour(self.app.get_color(self.app.brush))
+        self.color.Refresh()
 
+
 class Application(wx.App):
+
     def __init__(self, options):
-	self.options = options
-	wx.App.__init__(self)
+        self.options = options
+        wx.App.__init__(self)
 
     def initialize(self):
-	grass.use_temp_region()
+        grass.use_temp_region()
 
-	run('g.region', raster = self.inmap)
+        run('g.region', raster=self.inmap)
 
-	reg = grass.region()
-	for k, f in wind_keys.values():
-	    self.total[k] = (f)(reg[k])
+        reg = grass.region()
+        for k, f in wind_keys.values():
+            self.total[k] = (f)(reg[k])
 
-	if self.cols > self.total['cols']:
-	    self.cols = self.total['cols']
-	if self.rows > self.total['rows']:
-	    self.rows = self.total['rows']
+        if self.cols > self.total['cols']:
+            self.cols = self.total['cols']
+        if self.rows > self.total['rows']:
+            self.rows = self.total['rows']
 
-	tempbase = grass.tempfile()
-	grass.try_remove(tempbase)
+        tempbase = grass.tempfile()
+        grass.try_remove(tempbase)
 
-	self.tempfile = tempbase + '.ppm'
-	self.tempmap = 'tmp.d.rast.edit'
+        self.tempfile = tempbase + '.ppm'
+        self.tempmap = 'tmp.d.rast.edit'
 
-	atexit.register(self.cleanup)
+        atexit.register(self.cleanup)
 
-	run('g.copy', raster = (self.inmap, self.outmap), overwrite = True)
-	run('r.colors', map = self.outmap, rast = self.inmap)
+        run('g.copy', raster=(self.inmap, self.outmap), overwrite=True)
+        run('r.colors', map=self.outmap, rast=self.inmap)
 
     def cleanup(self):
-	grass.try_remove(self.tempfile)
-	run('g.remove', flags = 'f', type = 'raster', name = self.tempmap)
+        grass.try_remove(self.tempfile)
+        run('g.remove', flags='f', type='raster', name=self.tempmap)
 
     def finalize(self):
-	self.save_map()
-	sys.exit(0)
+        self.save_map()
+        sys.exit(0)
 
     def save_map(self):
-	p = grass.feed_command('r.in.ascii', input = '-', output = self.tempmap, quiet = True, overwrite = True)
-	outf = p.stdin
-	outf.write("north: %f\n" % self.wind['n'])
-	outf.write("south: %f\n" % self.wind['s'])
-	outf.write("east: %f\n"  % self.wind['e'])
-	outf.write("west: %f\n"  % self.wind['w'])
-	outf.write("rows: %d\n"  % self.wind['rows'])
-	outf.write("cols: %d\n"  % self.wind['cols'])
-	outf.write("null: *\n")
+        p = grass.feed_command(
+            'r.in.ascii',
+            input='-',
+            output=self.tempmap,
+            quiet=True,
+            overwrite=True)
+        outf = p.stdin
+        outf.write("north: %f\n" % self.wind['n'])
+        outf.write("south: %f\n" % self.wind['s'])
+        outf.write("east: %f\n" % self.wind['e'])
+        outf.write("west: %f\n" % self.wind['w'])
+        outf.write("rows: %d\n" % self.wind['rows'])
+        outf.write("cols: %d\n" % self.wind['cols'])
+        outf.write("null: *\n")
 
-	for row in range(self.wind['rows']):
-	    for col in range(self.wind['cols']):
-		if col > 0:
-		    outf.write(" ")
-		val = self.values[row][col]
-		if val and self.changed[row][col]:
-		    outf.write("%s" % val)
-		else:
-		    outf.write('*')
-	    outf.write("\n")
+        for row in range(self.wind['rows']):
+            for col in range(self.wind['cols']):
+                if col > 0:
+                    outf.write(" ")
+                val = self.values[row][col]
+                if val and self.changed[row][col]:
+                    outf.write("%s" % val)
+                else:
+                    outf.write('*')
+            outf.write("\n")
 
-	outf.close()
-	p.wait()
+        outf.close()
+        p.wait()
 
-	run('g.region', raster = self.inmap)
-	run('r.patch', input = (self.tempmap, self.outmap), output = self.outmap, overwrite = True)
-	run('r.colors', map = self.outmap, rast = self.inmap)
-	run('g.remove', flags = 'f', type = 'raster', name = self.tempmap)
+        run('g.region', raster=self.inmap)
+        run('r.patch',
+            input=(self.tempmap,
+                   self.outmap),
+            output=self.outmap,
+            overwrite=True)
+        run('r.colors', map=self.outmap, rast=self.inmap)
+        run('g.remove', flags='f', type='raster', name=self.tempmap)
 
     def read_header(self, infile):
-	wind = {}
-	for i in range(6):
-	    line = infile.readline().rstrip('\r\n')
-	    f = line.split(':')
-	    key = f[0]
-	    val = f[1].strip()
-	    (k, f) = wind_keys[key]
-	    wind[k] = (f)(val)
-	return wind
+        wind = {}
+        for i in range(6):
+            line = infile.readline().rstrip('\r\n')
+            f = line.split(':')
+            key = f[0]
+            val = f[1].strip()
+            (k, f) = wind_keys[key]
+            wind[k] = (f)(val)
+        return wind
 
     def read_data(self, infile):
-	values = []
-	for row in range(self.wind['rows']):
-	    line = infile.readline().rstrip('\r\n')
-	    values.append(line.split())
-	return values
+        values = []
+        for row in range(self.wind['rows']):
+            line = infile.readline().rstrip('\r\n')
+            values.append(line.split())
+        return values
 
     def load_map(self):
-	run('g.region', **self.wind)
+        run('g.region', **self.wind)
 
-	p = grass.pipe_command('r.out.ascii', input = self.inmap, quiet = True)
-	self.wind = self.read_header(p.stdout)
-	self.values = self.read_data(p.stdout)
-	self.changed = [[False for c in row] for row in self.values]
-	p.wait()
+        p = grass.pipe_command('r.out.ascii', input=self.inmap, quiet=True)
+        self.wind = self.read_header(p.stdout)
+        self.values = self.read_data(p.stdout)
+        self.changed = [[False for c in row] for row in self.values]
+        p.wait()
 
-	self.clear_changes()
+        self.clear_changes()
 
-	run('r.out.ppm', input = self.inmap, output = self.tempfile)
-	colorimg = wx.Image(self.tempfile)
-	grass.try_remove(self.tempfile)
+        run('r.out.ppm', input=self.inmap, output=self.tempfile)
+        colorimg = wx.Image(self.tempfile)
+        grass.try_remove(self.tempfile)
 
-	for row in range(self.wind['rows']):
-	    for col in range(self.wind['cols']):
-		val = self.values[row][col]
-		if val in self.colors:
-		    continue
-		r = colorimg.GetRed(col, row)
-		g = colorimg.GetGreen(col, row)
-		b = colorimg.GetBlue(col, row)
-		color = "#%02x%02x%02x" % (r, g, b)
-		self.colors[val] = color
+        for row in range(self.wind['rows']):
+            for col in range(self.wind['cols']):
+                val = self.values[row][col]
+                if val in self.colors:
+                    continue
+                r = colorimg.GetRed(col, row)
+                g = colorimg.GetGreen(col, row)
+                b = colorimg.GetBlue(col, row)
+                color = "#%02x%02x%02x" % (r, g, b)
+                self.colors[val] = color
 
-	colorimg.Destroy()
+        colorimg.Destroy()
 
     def load_aspect(self):
-	if not self.aspect:
-	    return
+        if not self.aspect:
+            return
 
-	p = grass.pipe_command('r.out.ascii', input = self.aspect, quiet = True)
-	self.read_header(p.stdout)
-	self.angles = self.read_data(p.stdout)
-	p.wait()
+        p = grass.pipe_command('r.out.ascii', input=self.aspect, quiet=True)
+        self.read_header(p.stdout)
+        self.angles = self.read_data(p.stdout)
+        p.wait()
 
     def clear_changes(self):
-	for row in range(self.wind['rows']):
-	    for col in range(self.wind['cols']):
-		self.changed[row][col] = 0
+        for row in range(self.wind['rows']):
+            for col in range(self.wind['cols']):
+                self.changed[row][col] = 0
 
     def update_window(self):
-	x0 = self.origin_x
-	y0 = self.origin_y
-	x1 = x0 + self.cols
-	y1 = y0 + self.rows
+        x0 = self.origin_x
+        y0 = self.origin_y
+        x1 = x0 + self.cols
+        y1 = y0 + self.rows
 
-	self.wind['n'] = self.total['n'] - y0 * self.total['nsres']
-	self.wind['s'] = self.total['n'] - y1 * self.total['nsres']
-	self.wind['w'] = self.total['w'] + x0 * self.total['ewres']
-	self.wind['e'] = self.total['w'] + x1 * self.total['ewres']
-	self.wind['rows'] = self.rows
-	self.wind['cols'] = self.cols
+        self.wind['n'] = self.total['n'] - y0 * self.total['nsres']
+        self.wind['s'] = self.total['n'] - y1 * self.total['nsres']
+        self.wind['w'] = self.total['w'] + x0 * self.total['ewres']
+        self.wind['e'] = self.total['w'] + x1 * self.total['ewres']
+        self.wind['rows'] = self.rows
+        self.wind['cols'] = self.cols
 
     def change_window(self):
-	self.save_map()
-	self.update_window()
-	self.load_map()
-	self.load_aspect()
-	self.refresh_canvas()
+        self.save_map()
+        self.update_window()
+        self.load_map()
+        self.load_aspect()
+        self.refresh_canvas()
 
     def force_window(self):
-	if self.origin_x < 0:
-	    self.origin_x = 0
-	if self.origin_x > self.total['cols'] - self.cols:
-	    self.origin_x = self.total['cols'] - self.cols
-	if self.origin_y < 0:
-	    self.origin_y = 0
-	if self.origin_y > self.total['rows'] - self.rows:
-	    self.origin_y = self.total['rows'] - self.rows
+        if self.origin_x < 0:
+            self.origin_x = 0
+        if self.origin_x > self.total['cols'] - self.cols:
+            self.origin_x = self.total['cols'] - self.cols
+        if self.origin_y < 0:
+            self.origin_y = 0
+        if self.origin_y > self.total['rows'] - self.rows:
+            self.origin_y = self.total['rows'] - self.rows
 
     def update_status(self, row, col):
-	self.status['row'] = row
-	self.status['col'] = col
-	self.status['x'] = self.wind['e'] + (col + 0.5) * (self.wind['e'] - self.wind['w']) / self.wind['cols']
-	self.status['y'] = self.wind['n'] - (row + 0.5) * (self.wind['n'] - self.wind['s']) / self.wind['rows']
-	self.status['value'] = self.values[row][col]
-	if self.angles:
-	    self.status['aspect'] = self.angles[row][col]
+        self.status['row'] = row
+        self.status['col'] = col
+        self.status['x'] = self.wind[
+            'e'] + (col + 0.5) * (self.wind['e'] - self.wind['w']) / self.wind['cols']
+        self.status['y'] = self.wind[
+            'n'] - (row + 0.5) * (self.wind['n'] - self.wind['s']) / self.wind['rows']
+        self.status['value'] = self.values[row][col]
+        if self.angles:
+            self.status['aspect'] = self.angles[row][col]
 
     def force_color(val):
-	run('g.region', rows = 1, cols = 1)
-	run('r.mapcalc', expression = "%s = %d" % (self.tempmap, val))
-	run('r.colors', map = self.tempmap, rast = self.inmap)
-	run('r.out.ppm', input = self.tempmap, out = self.tempfile)
-	run('g.remove', flags = 'f', type = 'raster', name = self.tempmap)
+        run('g.region', rows=1, cols=1)
+        run('r.mapcalc', expression="%s = %d" % (self.tempmap, val))
+        run('r.colors', map=self.tempmap, rast=self.inmap)
+        run('r.out.ppm', input=self.tempmap, out=self.tempfile)
+        run('g.remove', flags='f', type='raster', name=self.tempmap)
 
-	tempimg = wx.Image(self.tempfile)
-	grass.try_remove(self.tempfile)
+        tempimg = wx.Image(self.tempfile)
+        grass.try_remove(self.tempfile)
 
-	rgb = tempimg.get(0, 0)
-	color = "#%02x%02x%02x" % rgb
-	self.colors[val] = color
-	tempimg.delete()
+        rgb = tempimg.get(0, 0)
+        color = "#%02x%02x%02x" % rgb
+        self.colors[val] = color
+        tempimg.delete()
 
     def get_color(self, val):
-	if val not in self.colors:
-	    try:
-		self.force_color(val)
-	    except:
-		self.colors[val] = "#ffffff"
+        if val not in self.colors:
+            try:
+                self.force_color(val)
+            except:
+                self.colors[val] = "#ffffff"
 
-	return self.colors[val]
+        return self.colors[val]
 
     def refresh_canvas(self):
-	self.frame.canvas.Refresh()
+        self.frame.canvas.Refresh()
 
     def make_ui(self):
-	self.frame = MainWindow(self)
-	self.SetTopWindow(self.frame)
-	self.frame.Show()
-	self.overview = OverviewWindow(self)
-	self.overview.Show()
+        self.frame = MainWindow(self)
+        self.SetTopWindow(self.frame)
+        self.frame.Show()
+        self.overview = OverviewWindow(self)
+        self.overview.Show()
 
     def OnInit(self):
-	self.outmap = self.options['output']
-	self.inmap  = self.options['input']
-	self.aspect = self.options['aspect']
-	self.width  = int(self.options['width'])
-	self.height = int(self.options['height'])
-	self.size   = int(self.options['size'])
-	self.rows   = int(self.options['rows'])
-	self.cols   = int(self.options['cols'])
+        self.outmap = self.options['output']
+        self.inmap = self.options['input']
+        self.aspect = self.options['aspect']
+        self.width = int(self.options['width'])
+        self.height = int(self.options['height'])
+        self.size = int(self.options['size'])
+        self.rows = int(self.options['rows'])
+        self.cols = int(self.options['cols'])
 
-	self.status = {
-	    'row': '',
-	    'col': '',
-	    'x': '',
-	    'y': '',
-	    'value': '',
-	    'aspect': ''
-	}
+        self.status = {
+            'row': '',
+            'col': '',
+            'x': '',
+            'y': '',
+            'value': '',
+            'aspect': ''
+        }
 
-	self.values = None
-	self.changed = None
-	self.angles = None
-	self.colors = {}
-	self.brush = '*'
-	self.origin_x = 0
-	self.origin_y = 0
-	self.wind = {}
-	self.total = {}
+        self.values = None
+        self.changed = None
+        self.angles = None
+        self.colors = {}
+        self.brush = '*'
+        self.origin_x = 0
+        self.origin_y = 0
+        self.wind = {}
+        self.total = {}
 
-	self.initialize()
-	self.update_window()
-	self.make_ui()
-	self.load_map()
-	self.load_aspect()
-	self.refresh_canvas()
+        self.initialize()
+        self.update_window()
+        self.make_ui()
+        self.load_map()
+        self.load_aspect()
+        self.refresh_canvas()
 
-	return True
+        return True
 
 if __name__ == "__main__":
     options, flags = grass.parser()

Modified: grass/trunk/scripts/d.rast.leg/d.rast.leg.py
===================================================================
--- grass/trunk/scripts/d.rast.leg/d.rast.leg.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/d.rast.leg/d.rast.leg.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -125,8 +125,10 @@
     ncats = len(cats.strip().split('\n'))
 
     # 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)
 

Modified: grass/trunk/scripts/d.redraw/d.redraw.py
===================================================================
--- grass/trunk/scripts/d.redraw/d.redraw.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/d.redraw/d.redraw.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -26,6 +26,7 @@
 from grass.script import core as grass
 from grass.script.utils import split
 
+
 def main():
     mon = grass.gisenv().get('MONITOR', None)
     if not mon:
@@ -38,25 +39,25 @@
     try:
         fd = open(monCmd, 'r')
         cmdList = fd.readlines()
-        
+
         grass.run_command('d.erase')
-        
+
         for cmd in cmdList:
             grass.call(split(cmd))
     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()
-    
+
     # restore cmd file
     try:
         fd = open(monCmd, "w")
         fd.writelines(cmdList)
     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
 
 if __name__ == "__main__":

Modified: grass/trunk/scripts/db.dropcolumn/db.dropcolumn.py
===================================================================
--- grass/trunk/scripts/db.dropcolumn/db.dropcolumn.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/db.dropcolumn/db.dropcolumn.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -5,7 +5,7 @@
 # MODULE:       db.dropcolumn
 # AUTHOR(S):   	Markus Neteler
 #               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
 #               - with special trick for SQLite
 # COPYRIGHT:    (C) 2007, 2012 by Markus Neteler and the GRASS Development Team
@@ -36,10 +36,10 @@
 #%end
 
 import sys
-import os
 import string
-import grass.script as grass
+
 from grass.exceptions import CalledModuleError
+import grass.script as gscript
 
 
 def main():
@@ -48,66 +48,67 @@
     force = flags['f']
 
     # 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']
     driver = kv['driver']
     # schema needed for PG?
 
     if force:
-	grass.message(_("Forcing ..."))
+        gscript.message(_("Forcing ..."))
 
     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:
-	grass.fatal(_("Column <%s> not found in table") % column)
+        gscript.fatal(_("Column <%s> not found in table") % column)
 
     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":
-	#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]))
+        # 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)
+        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)
+        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:
-	sql = "ALTER TABLE %s DROP COLUMN %s" % (table, column)
+        sql = "ALTER TABLE %s DROP COLUMN %s" % (table, column)
 
     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:
-        grass.fatal(_("Cannot continue (problem deleting column)"))
+        gscript.fatal(_("Cannot continue (problem deleting column)"))
 
     return 0
 
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     sys.exit(main())

Modified: grass/trunk/scripts/db.in.ogr/db.in.ogr.py
===================================================================
--- grass/trunk/scripts/db.in.ogr/db.in.ogr.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/db.in.ogr/db.in.ogr.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -72,74 +72,76 @@
     mapset = grass.gisenv()['MAPSET']
 
     if db_table:
-	input = db_table
+        input = db_table
 
     if not output:
-	tmpname = input.replace('.', '_')
-	output = grass.basename(tmpname)
+        tmpname = input.replace('.', '_')
+        output = grass.basename(tmpname)
 
     # check if table exists
     try:
         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()
     except CalledModuleError:
         # check connection parameters, set if uninitialized
         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():
         if l == output:
             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
             else:
                 grass.fatal(_("Table <%s> already exists") % output)
-                
+
     # treat DB as real vector map...
-    if db_table:
-	layer = db_table
-    else:
-	layer = None
+    layer = db_table if db_table else None
 
     vopts = {}
     if options['encoding']:
         vopts['encoding'] = options['encoding']
-    
+
     try:
         grass.run_command('v.in.ogr', flags='o', input=input, output=output,
                           layer=layer, quiet=True, **vopts)
     except CalledModuleError:
         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:
             grass.fatal(_("Input DSN <%s> not found or not readable") % input)
 
     # rename ID col if requested from cat to new name
     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
-    vectfile = grass.find_file(output, element = 'vector', mapset = mapset)['file']
+    vectfile = grass.find_file(output, element='vector', mapset=mapset)['file']
     if not vectfile:
-	grass.fatal(_("Something went wrong. Should not happen"))
+        grass.fatal(_("Something went wrong. Should not happen"))
     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)
     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()
-    
+
     records = grass.db_describe(output)['nrows']
     grass.message(_("Imported table <%s> with %d rows") % (output, records))
 

Modified: grass/trunk/scripts/db.out.ogr/db.out.ogr.py
===================================================================
--- grass/trunk/scripts/db.out.ogr/db.out.ogr.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/db.out.ogr/db.out.ogr.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -54,10 +54,10 @@
 #% required: no
 #%end
 
-import sys
 import os
+
 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
 
 
@@ -69,54 +69,52 @@
     table = options['table']
 
     if format.lower() == 'dbf':
-	format = "ESRI_Shapefile"
+        format = "ESRI_Shapefile"
 
     if format.lower() == 'csv':
-	olayer = basename(output, 'csv')
+        olayer = basename(output, 'csv')
     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'
-    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:
         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:
-            grass.fatal(_("Module <%s> failed") % 'v.out.ogr')
+            gcore.fatal(_("Module <%s> failed") % 'v.out.ogr')
 
     else:
         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,
                               format=format, type='point,line,area')
         except CalledModuleError:
-            grass.fatal(_("Module <%s> failed") % 'v.out.ogr')
+            gcore.fatal(_("Module <%s> failed") % 'v.out.ogr')
 
     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':
-	outname = output + '.csv'
+        outname = output + '.csv'
     else:
-	outname = input
+        outname = input
 
-    grass.message(_("Exported table <%s>") % outname)
+    gcore.message(_("Exported table <%s>") % outname)
 
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gcore.parser()
     main()
-

Modified: grass/trunk/scripts/db.test/db.test.py
===================================================================
--- grass/trunk/scripts/db.test/db.test.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/db.test/db.test.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -28,61 +28,62 @@
 
 import sys
 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.exceptions import CalledModuleError
 
+
 def main():
     test_file = options['test']
 
-    expected = grass.tempfile()
-    result = grass.tempfile()
+    expected = gcore.tempfile()
+    result = gcore.tempfile()
 
     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)
     inf = file(infile)
 
     while True:
-	type = inf.readline()
-	if not type:
-	    break
-	type = type.rstrip('\r\n')
+        type = inf.readline()
+        if not type:
+            break
+        type = type.rstrip('\r\n')
 
-	sql = inf.readline().rstrip('\r\n')
-	sys.stdout.write(sql + '\n')
+        sql = inf.readline().rstrip('\r\n')
+        sys.stdout.write(sql + '\n')
 
-	# Copy expected result to temp file
-
+        # Copy expected result to temp file
         try:
             if type == 'X':
-                grass.write_command('db.execute', input = '-', stdin = sql + '\n')
+                gcore.write_command('db.execute', input='-', stdin=sql + '\n')
             else:
                 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()
 
         except CalledModuleError:
-            grass.error("EXECUTE: ******** ERROR ********")
+            gcore.error("EXECUTE: ******** ERROR ********")
         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__":
-    options, flags = grass.parser()
+    options, flags = gcore.parser()
     main()
-

Modified: grass/trunk/scripts/db.univar/db.univar.py
===================================================================
--- grass/trunk/scripts/db.univar/db.univar.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/db.univar/db.univar.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -56,25 +56,26 @@
 #%end
 
 import sys
-import os
 import atexit
 import math
 
-import grass.script as grass 
+import grass.script as gscript
 
+
 def cleanup():
     for ext in ['', '.sort']:
-        grass.try_remove(tmp + ext)
+        gscript.try_remove(tmp + ext)
 
+
 def sortfile(infile, outfile):
     inf = file(infile, 'r')
     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:
         # 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()
         for i in range(len(lines)):
             lines[i] = float(lines[i].rstrip('\r\n'))
@@ -85,9 +86,10 @@
     inf.close()
     outf.close()
 
+
 def main():
     global tmp
-    tmp = grass.tempfile()
+    tmp = gscript.tempfile()
 
     extend = flags['e']
     shellstyle = flags['g']
@@ -100,21 +102,22 @@
 
     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:
-        grass.fatal(_("Unable to describe table <%s>") % table)
+        gscript.fatal(_("Unable to describe table <%s>") % table)
     found = False
     for cname, ctype, cwidth in desc_table['cols']:
         if cname == column:
             found = True
             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:
-        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:
-        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)
     if where:
@@ -127,20 +130,20 @@
         driver = None
 
     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()
 
     # check if result is empty
     tmpf = file(tmp)
     if tmpf.read(1) == '':
-        grass.fatal(_("Table <%s> contains no data.") % table)
+        gscript.fatal(_("Table <%s> contains no data.") % table)
         tmpf.close()
 
     # calculate statistics
     if not shellstyle:
-        grass.verbose(_("Calculating statistics..."))
+        gscript.verbose(_("Calculating statistics..."))
 
     N = 0
     sum = 0.0
@@ -151,8 +154,8 @@
 
     tmpf = file(tmp)
     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'))
         N += 1
         sum += x
@@ -163,30 +166,43 @@
     tmpf.close()
 
     if N <= 0:
-        grass.fatal(_("No non-null values found"))
+        gscript.fatal(_("No non-null values found"))
 
     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:
-        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:
         return
@@ -194,27 +210,26 @@
     # preparations:
     sortfile(tmp, tmp + ".sort")
 
-    number = N
     odd = N % 2
-    eostr = ['even','odd'][odd]
+    eostr = ['even', 'odd'][odd]
 
     q25pos = round(N * 0.25)
     if q25pos == 0:
-	q25pos = 1
+        q25pos = 1
     q50apos = round(N * 0.50)
     if q50apos == 0:
-	q50apos = 1
+        q50apos = 1
     q50bpos = q50apos + (1 - odd)
     q75pos = round(N * 0.75)
     if q75pos == 0:
-	q75pos = 1
+        q75pos = 1
 
     ppos = {}
     pval = {}
     for i in range(len(perc)):
         ppos[i] = round(N * perc[i] / 100)
-	if ppos[i] == 0:
-	    ppos[i] = 1
+        if ppos[i] == 0:
+            ppos[i] = 1
         pval[i] = 0
 
     inf = file(tmp + ".sort")
@@ -240,27 +255,45 @@
         sys.stdout.write("Median (%s N): %.15g\n" % (eostr, q50))
         sys.stdout.write("3rd Quartile: %.15g\n" % q75)
         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:
-                    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:
-                    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:
-                    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:
-                    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:
-                sys.stdout.write("%.15g Percentile: %.15g\n"% (perc[i], pval[i]))
+                sys.stdout.write(
+                    "%.15g Percentile: %.15g\n" %
+                    (perc[i], pval[i]))
     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)):
             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__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     atexit.register(cleanup)
     main()

Modified: grass/trunk/scripts/g.extension/g.extension.py
===================================================================
--- grass/trunk/scripts/g.extension/g.extension.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/g.extension/g.extension.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -314,7 +314,7 @@
             ))
         else:
             ret.append(tnode.get('name').strip())
-    
+
     return ret
 
 # list extensions (read XML file from grass.osgeo.org/addons)
@@ -391,6 +391,7 @@
 
     return tlist
 
+
 def get_module_files(mnode):
     """Return list of module files
 
@@ -403,6 +404,7 @@
 
     return flist
 
+
 def get_module_executables(mnode):
     """Return list of module executables
 
@@ -411,15 +413,16 @@
     flist = []
     for filepath in get_module_files(mnode):
         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)
             if sys.platform == 'win32':
                 filename = os.path.splitext(filename)[0]
             flist.append(filename)
-    
+
     return flist
 
+
 def get_optional_params(mnode):
     """Return description and keywords as a tuple
 
@@ -920,7 +923,7 @@
     """Install extension on MS Windows"""
     grass.message(_("Downloading precompiled GRASS Addons <%s>...") %
                   options['extension'])
-    
+
     # build base URL
     if build_platform == 'x86_64':
         platform = build_platform
@@ -929,29 +932,29 @@
     base_url = "http://wingrass.fsv.cvut.cz/" \
                "grass%(major)s%(minor)s/%(platform)s/addons/" \
                "grass-%(major)s.%(minor)s.%(patch)s" % \
-               {'platform' : platform,
+               {'platform': platform,
                 'major': version[0], 'minor': version[1],
                 'patch': version[2]}
 
     # resolve ZIP URL
     source, url = resolve_source_code(url='{}/{}.zip'.format(base_url, name))
-    
+
     # to hide non-error messages from subprocesses
     if grass.verbosity() <= 2:
         outdev = open(os.devnull, 'w')
     else:
         outdev = sys.stdout
-    
+
     # download Addons ZIP file
     os.chdir(TMPDIR)  # this is just to not leave something behind
     srcdir = os.path.join(TMPDIR, 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
     move_extracted_files(extract_dir=srcdir, target_dir=options['prefix'],
                          files=os.listdir(srcdir))
-    
+
     return 0
 
 
@@ -1090,7 +1093,7 @@
         f, h = urlretrieve(url, zip_name)
         if h.get('content-type', '') != 'application/zip':
             grass.fatal(_("Extension <%s> not found") % name)
-            
+
         extract_zip(name=zip_name, directory=directory, tmpdir=tmpdir)
         fix_newlines(directory)
     elif source.startswith('remote_') and \
@@ -1718,9 +1721,9 @@
     global TMPDIR
     TMPDIR = tempfile.mkdtemp()
     atexit.register(cleanup)
-    
+
     grass_version = grass.version()
     version = grass_version['version'].split('.')
     build_platform = grass_version['build_platform'].split('-', 1)[0]
-    
+
     sys.exit(main())

Modified: grass/trunk/scripts/g.extension/testsuite/test_addons_modules.py
===================================================================
--- grass/trunk/scripts/g.extension/testsuite/test_addons_modules.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/g.extension/testsuite/test_addons_modules.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -99,7 +99,7 @@
         """Test installing extension from local .tar.gz"""
         self.assertModule('g.extension', extension='r.plus.example',
                           url=os.path.join(self.path,
-                                              'r.plus.example.tar.gz'),
+                                           'r.plus.example.tar.gz'),
                           prefix=self.install_prefix)
         for file in self.files:
             self.assertFileExists(file)

Modified: grass/trunk/scripts/g.extension.all/g.extension.all.py
===================================================================
--- grass/trunk/scripts/g.extension.all/g.extension.all.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/g.extension.all/g.extension.all.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -6,7 +6,7 @@
 #
 # 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
 #
@@ -35,23 +35,23 @@
 #% key: f
 #% label: Force operation (required for removal)
 #% end
-
+from __future__ import print_function
 import os
 import sys
 
 try:
     import xml.etree.ElementTree as etree
 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
 
 
 def get_extensions():
     addon_base = os.getenv('GRASS_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')
     if not os.path.exists(fXML):
         return []
@@ -60,51 +60,56 @@
     fo = open(fXML, 'r')
     try:
         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()
         return []
-    
+
     fo.close()
-    
-    libgis_rev = grass.version()['libgis_revision']
+
+    libgis_rev = gscript.version()['libgis_revision']
     ret = list()
     for tnode in tree.findall('task'):
         gnode = tnode.find('libgis')
         if gnode is not None and \
                 gnode.get('revision', '') != libgis_rev:
             ret.append(tnode.get('name'))
-    
+
     return ret
 
+
 def main():
     remove = options['operation'] == 'remove'
     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:
         extensions = get_extensions()
-    
+
     if not extensions:
         if remove:
-            grass.info(_("No extension found. Nothing to remove."))
+            gscript.info(_("No extension found. Nothing to remove."))
         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
-    
+
     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
-    
+
     for ext in extensions:
-        grass.message('-' * 60)
+        gscript.message('-' * 60)
         if remove:
-            grass.message(_("Removing extension <%s>...") % ext)
+            gscript.message(_("Removing extension <%s>...") % ext)
         else:
-            grass.message(_("Reinstalling extension <%s>...") % ext)
-        grass.message('-' * 60)
+            gscript.message(_("Reinstalling extension <%s>...") % ext)
+        gscript.message('-' * 60)
         if remove:
             operation = 'remove'
             operation_flags = 'f'
@@ -112,13 +117,13 @@
             operation = 'add'
             operation_flags = ''
         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:
-            grass.error(_("Unable to process extension:%s") % ext)
+            gscript.error(_("Unable to process extension:%s") % ext)
 
     return 0
 
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     sys.exit(main())

Modified: grass/trunk/scripts/g.manual/g.manual.py
===================================================================
--- grass/trunk/scripts/g.manual/g.manual.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/g.manual/g.manual.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -60,6 +60,7 @@
 from grass.script.utils import basename
 from grass.script import core as grass
 
+
 def start_browser(entry):
     if browser and \
        browser not in ('xdg-open', 'start') and \
@@ -86,7 +87,7 @@
         webbrowser.register(browser_name, None)
 
     grass.verbose(_("Starting browser '%(browser)s' for manual"
-                    " entry '%(entry)s'...") % \
+                    " entry '%(entry)s'...") %
                   dict(browser=browser_name, entry=entry))
 
     try:
@@ -95,6 +96,7 @@
         grass.fatal(_("Error starting browser '%(browser)s' for HTML file"
                       " '%(path)s'") % dict(browser=browser, path=path))
 
+
 def start_man(entry):
     path = os.path.join(gisbase, 'docs', 'man', 'man1', entry + '.1')
     if not os.path.exists(path) and os.getenv('GRASS_ADDON_BASE'):
@@ -106,6 +108,7 @@
             grass.fatal(_("Error starting 'man' for '%s'") % path)
     grass.fatal(_("No manual page entry for '%s'") % entry)
 
+
 def main():
     global gisbase, browser, browser_name
 
@@ -115,7 +118,7 @@
     special = None
     if flags['i']:
         special = 'index'
-    elif flags ['t']:
+    elif flags['t']:
         special = 'topics'
 
     if flags['m']:
@@ -123,7 +126,7 @@
     else:
         start = start_browser
 
-    entry  = options['entry']
+    entry = options['entry']
     gisbase = os.environ['GISBASE']
     browser = os.getenv('GRASS_HTML_BROWSER', '')
 

Modified: grass/trunk/scripts/g.search.modules/g.search.modules.py
===================================================================
--- grass/trunk/scripts/g.search.modules/g.search.modules.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/g.search.modules/g.search.modules.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -50,7 +50,7 @@
 #% description: JSON format
 #% guisection: Output
 #%end
-
+from __future__ import print_function
 import os
 import sys
 
@@ -58,12 +58,13 @@
 from grass.script import core as grass
 
 try:
-    import xml.etree.ElementTree   as etree
+    import xml.etree.ElementTree as etree
 except ImportError:
-    import elementtree.ElementTree as etree # Python <= 2.4
+    import elementtree.ElementTree as etree  # Python <= 2.4
 
-COLORIZE=False
+COLORIZE = False
 
+
 def main():
     global COLORIZE
     keywords = options['keyword'].lower().split(',')
@@ -79,8 +80,9 @@
 
     modules = _search_module(keywords, AND, manpages)
 
-    print_results(modules, out_format) 
+    print_results(modules, out_format)
 
+
 def print_results(data, out_format=None):
     """
     Print result of the searching method
@@ -107,31 +109,35 @@
     elif out_format == 'json':
         _print_results_json(data)
 
+
 def _print_results_shell(data):
     """Print just the name attribute"""
 
     for item in data:
-        print item['name']
+        print(item['name'])
 
+
 def _print_results_json(data):
     """Print JSON output"""
 
     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):
 
     import textwrap
 
     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']:
             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:
-                print line
+                print(line)
 
+
 def colorize(text, attrs=None, pattern=None):
     """Colorize given text input
 
@@ -140,7 +146,6 @@
     :param string pattern: text to be highlighted in input text
     :return: colored string
     """
-    
 
     if COLORIZE:
         try:
@@ -156,6 +161,7 @@
     else:
         return colored(text, attrs=attrs)
 
+
 def _search_module(keywords, logical_and=False, manpages=False):
     """Search modules by given keywords
 
@@ -200,11 +206,11 @@
                     found = [True]
 
                 description = colorize(description,
-                                        attrs=['underline'],
-                                        pattern=keyword)
+                                       attrs=['underline'],
+                                       pattern=keyword)
                 module_keywords = colorize(module_keywords,
-                                            attrs=['underline'],
-                                            pattern=keyword)
+                                           attrs=['underline'],
+                                           pattern=keyword)
 
         if False not in found:
             found_modules.append({
@@ -217,8 +223,9 @@
 
     return found_modules
 
+
 def _basic_search(pattern, name, description, module_keywords):
-    
+
     if name.lower().find(pattern) > -1 or\
        description.lower().find(pattern) > -1 or\
        module_keywords.lower().find(pattern) > -1:
@@ -227,6 +234,7 @@
     else:
         return False
 
+
 def _manpage_search(pattern, name):
 
     manpage = grass.read_command('g.manual', flags='m', entry=name)

Modified: grass/trunk/scripts/g.search.modules/testsuite/test_g_search_modules.py
===================================================================
--- grass/trunk/scripts/g.search.modules/testsuite/test_g_search_modules.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/g.search.modules/testsuite/test_g_search_modules.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -52,7 +52,7 @@
         stdout = module.outputs.stdout.split()
         self.assertEqual(stdout[0],
                          termcolor.colored('r.watershed',
-                         attrs=['bold']))
+                                           attrs=['bold']))
 
     def test_manual_pages(self):
         module = SimpleModule('g.search.modules', keyword="kapri", flags="gm")

Modified: grass/trunk/scripts/i.colors.enhance/i.colors.enhance.py
===================================================================
--- grass/trunk/scripts/i.colors.enhance/i.colors.enhance.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/i.colors.enhance/i.colors.enhance.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -8,7 +8,7 @@
 #		Hamish Bowman, scripting enhancements
 #               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)
 #
 # COPYRIGHT:	(C) 2006, 2008, 2012-2014 by the GRASS Development Team
@@ -68,9 +68,9 @@
 #%end
 
 import sys
-import os
-import string
-import grass.script as grass
+
+import grass.script as gscript
+
 try:
     # new for python 2.6, in 2.5 it may be easy_install'd.
     import multiprocessing as mp
@@ -85,14 +85,16 @@
     val2 = percentiles[1]
     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_str2 = s.splitlines()[1].split(':')[2]
     return (float(val_str1), float(val_str2))
 
 # wrapper to handle multiprocesses communications back to the parent
+
+
 def get_percentile_mp(map, percentiles, conn):
     # Process() doesn't like storing connection parts in
     #  separate dictionaries, only wants to pass through tuples,
@@ -101,19 +103,16 @@
     output_pipe, input_pipe = conn
     input_pipe.close()
     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.close()
 
+
 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():
@@ -124,7 +123,7 @@
     full = flags['f']
     preserve = flags['p']
     reset = flags['r']
-    
+
     global do_mp
 
     if flags['s']:
@@ -135,92 +134,90 @@
     # must be more than "2" ?
 
     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:
-	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 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:
-	all_max = 0
-	all_min = 999999
+        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)
+        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)
 
-	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)
+            # 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:
-    mapset = grass.gisenv()['MAPSET']
+    mapset = gscript.gisenv()['MAPSET']
     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__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     main()

Modified: grass/trunk/scripts/i.image.mosaic/i.image.mosaic.py
===================================================================
--- grass/trunk/scripts/i.image.mosaic/i.image.mosaic.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/i.image.mosaic/i.image.mosaic.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -32,67 +32,70 @@
 #%end
 #%option G_OPT_R_OUTPUT
 #%end
+from __future__ import print_function
 
-import sys
-import os
-import grass.script as grass
+import grass.script as gscript
 
+
 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:
-	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()
 
+
 def get_limit(map):
-    return grass.raster_info(map)['max']
+    return gscript.raster_info(map)['max']
 
+
 def make_expression(i, count):
     if i > count:
-	return "null()"
+        return "null()"
     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():
     images = options['input'].split(',')
     output = options['output']
 
     count = len(images)
+    msg = _('Do not forget to set region properly to cover all images.')
+    gscript.warning(msg)
 
-    grass.warning(_('Do not forget to set region properly to cover all images.'))
-
     offset = 0
     offsets = []
     parms = {}
     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):
-	print img, offset
-	copy_colors(p.stdin, img, offset)
+        print(img, offset)
+        copy_colors(p.stdin, img, offset)
     p.stdin.close()
     p.wait()
 
-    grass.message(_("Done. Raster map <%s> created.") % output)
+    gscript.message(_("Done. Raster map <%s> created.") % output)
 
     # write cmd history:
-    grass.raster_history(output)
+    gscript.raster_history(output)
 
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     main()

Modified: grass/trunk/scripts/i.in.spotvgt/i.in.spotvgt.py
===================================================================
--- grass/trunk/scripts/i.in.spotvgt/i.in.spotvgt.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/i.in.spotvgt/i.in.spotvgt.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -23,7 +23,7 @@
 #      -  gdal: http://www.gdal.org
 #
 # 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.
 # * GDAL coordinates refer to the corner of a pixel
 #   -> correction of 0001/0001_LOG.TXT coordinates by 0.5 pixel
@@ -48,7 +48,7 @@
 import os
 import atexit
 import string
-import grass.script as grass
+import grass.script as gscript
 from grass.exceptions import CalledModuleError
 
 
@@ -67,103 +67,109 @@
  </VRTRasterBand>
 </VRTDataset>"""
 
-#### a function for writing VRT files
+# a function for writing VRT files
+
+
 def create_VRT_file(projfile, vrtfile, infile):
     fh = file(projfile)
     kv = {}
     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()
 
     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']
-    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
-    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)
-    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.write(s)
     outf.close()
 
+
 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():
     global vrtfile, tmpfile
 
-    infile  = options['input']
+    infile = options['input']
     rast = options['output']
     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())
-    tmpfile = grass.tempfile()
+    tmpfile = gscript.tempfile()
 
-    ################### let's go
+    # let's go
 
     spotdir = os.path.dirname(infile)
-    spotname = grass.basename(infile, 'hdf')
+    spotname = gscript.basename(infile, 'hdf')
 
     if rast:
-	name = rast
+        name = rast
     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'):
-	grass.fatal(_("Please extract %s before import.") % infile)
+        gscript.fatal(_("Please extract %s before import.") % infile)
 
     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:
-	pass
+        pass
 
-    ### create VRT header for NDVI
+    # create VRT header for NDVI
 
     projfile = os.path.join(spotdir, "0001_LOG.TXT")
     vrtfile = tmpfile + '.vrt'
 
     # first process the NDVI:
-    grass.try_remove(vrtfile)
+    gscript.try_remove(vrtfile)
     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:
-        grass.run_command('r.in.gdal', input=vrtfile, output=name)
+        gscript.run_command('r.in.gdal', input=vrtfile, output=name)
     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 ?
     # Real NDVI =coefficient a * Digital Number + coefficient b
     #           = a * DN +b
@@ -173,28 +179,29 @@
 
     # clone current 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)
-    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:
-    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:
-    
-    #SM Status Map
+
+    # SM Status Map
     # 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 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
@@ -205,7 +212,7 @@
     # Bit NR 0:	0	1	0		1
     # 		clear	shadow	uncertain	cloud
     #
-    #Note:
+    # Note:
     # pos 7     6    5    4    3    2   1   0 (bit position)
     #   128    64   32   16    8    4   2   1 (values for 8 bit)
     #
@@ -218,54 +225,55 @@
     # A good map threshold: >= 248
 
     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)
+        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'
+        # let's import the SM quality map...
+        smfile = name + '.sm'
         try:
-            grass.run_command('r.in.gdal', input=vrtfile, output=smfile)
+            gscript.run_command('r.in.gdal', input=vrtfile, output=smfile)
         except CalledModuleError:
-            grass.fatal(_("An error occurred. Stop."))
+            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'
-	    ]]
-	grass.write_command('r.colors', map = smfile, rules = '-', stdin = rules)
+        # 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)
 
-	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..."))
+        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
-	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)
+        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:
-	grass.raster_history(smfile)
-	grass.raster_history(filtfile)
+        # write cmd history:
+        gscript.raster_history(smfile)
+        gscript.raster_history(filtfile)
 
-    grass.message(_("Done."))
+    gscript.message(_("Done."))
 
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     atexit.register(cleanup)
     main()
-

Modified: grass/trunk/scripts/i.oif/i.oif.py
===================================================================
--- grass/trunk/scripts/i.oif/i.oif.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/i.oif/i.oif.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -121,7 +121,6 @@
             kv = parse_key_val(pout[band])
             stddev[band] = float(kv['stddev'])
 
-
     grass.message(_("Calculating Correlation Matrix..."))
     correlation = {}
     s = grass.read_command('r.covar', flags='r', map=[band for band in bands],
@@ -141,7 +140,7 @@
         oif.append((oifcalc(stddev, correlation, *p), p))
     oif.sort(reverse=True)
 
-    grass.verbose(_("The Optimum Index Factor analysis result " \
+    grass.verbose(_("The Optimum Index Factor analysis result "
                     "(best combination shown first):"))
 
     if shell:

Modified: grass/trunk/scripts/i.spectral/i.spectral.py
===================================================================
--- grass/trunk/scripts/i.spectral/i.spectral.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/i.spectral/i.spectral.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -20,7 +20,7 @@
 #
 # written by Markus Neteler 18. August 1998
 #            neteler geog.uni-hannover.de
-# 
+#
 # bugfix: 25. Nov.98/20. Jan. 1999
 # 3 March 2006: Added multiple images and group support by Francesco Pirotti - CIRGEO
 #
@@ -77,20 +77,22 @@
 import os
 import atexit
 from grass.script.utils import try_rmdir
-from grass.script import core as grass
+from grass.script import core as gcore
 
 
 def cleanup():
     try_rmdir(tmp_dir)
 
+
 def write2textf(what, output):
     outf = open(output, 'w')
-    i=0
+    i = 0
     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()
 
+
 def draw_gnuplot(what, xlabels, output, img_format, coord_legend):
     xrange = 0
 
@@ -107,12 +109,12 @@
     if output:
         if img_format == 'png':
             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"
-	elif img_format == 'svg':
+        elif img_format == 'svg':
             term_opts = "svg size 825,550 dynamic solid"
         else:
-            grass.fatal(_("Programmer error (%s)") % img_format)
+            gcore.fatal(_("Programmer error (%s)") % img_format)
 
         lines += [
             "set term " + term_opts,
@@ -152,9 +154,9 @@
     plotf.close()
 
     if output:
-        grass.call(['gnuplot', plotfile])
+        gcore.call(['gnuplot', plotfile])
     else:
-        grass.call(['gnuplot', '-persist', plotfile])
+        gcore.call(['gnuplot', '-persist', plotfile])
 
 
 def draw_linegraph(what):
@@ -175,7 +177,7 @@
         yf.close()
         yfiles.append(yfile)
 
-    sienna = '#%02x%02x%02x' % (160,  82, 45)
+    sienna = '#%02x%02x%02x' % (160, 82, 45)
     coral = '#%02x%02x%02x' % (255, 127, 80)
     gp_colors = ['red', 'green', 'blue', 'magenta', 'cyan', sienna, 'orange',
                  coral]
@@ -185,7 +187,7 @@
         colors += gp_colors
     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',
                       x_title='Bands', y_title='DN Value')
 
@@ -201,26 +203,26 @@
     textfile = flags['t']
 
     global tmp_dir
-    tmp_dir = grass.tempdir()
-    
+    tmp_dir = gcore.tempdir()
+
     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:
-        grass.fatal(_("group= and raster= are mutually exclusive"))
+        gcore.fatal(_("group= and raster= are mutually exclusive"))
 
     # -t needs an output filename
     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
-    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
     if group:
         # 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()
     else:
         # get data from list of files and set the x-axis labels
@@ -231,10 +233,10 @@
 
     # get y-data for gnuplot-data file
     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)
     if len(s) == 0:
-        grass.fatal(_('No data returned from query'))
+        gcore.fatal(_('No data returned from query'))
 
     for l in s.splitlines():
         f = l.split('|')
@@ -254,6 +256,6 @@
         draw_linegraph(what)
 
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gcore.parser()
     atexit.register(cleanup)
     main()

Modified: grass/trunk/scripts/i.tasscap/i.tasscap.py
===================================================================
--- grass/trunk/scripts/i.tasscap/i.tasscap.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/i.tasscap/i.tasscap.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -75,24 +75,24 @@
 
 # weights for 6 Landsat bands: TM4, TM5, TM7, OLI
 # 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
@@ -167,8 +167,8 @@
 
     # assign "Data Description" field in all four component maps
     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"))
 

Modified: grass/trunk/scripts/m.proj/m.proj.py
===================================================================
--- grass/trunk/scripts/m.proj/m.proj.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/m.proj/m.proj.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -95,10 +95,11 @@
 import os
 import threading
 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):
+
     def __init__(self, ifs, inf, outf):
         threading.Thread.__init__(self)
         self.ifs = ifs
@@ -131,28 +132,28 @@
     include_header = flags['c']
 
     # check for cs2cs
-    if not grass.find_program('cs2cs'):
-        grass.fatal(_(
+    if not gcore.find_program('cs2cs'):
+        gcore.fatal(_(
             "cs2cs program not found, install PROJ.4 first: \
             http://proj.maptools.org"))
 
     # check for overenthusiasm
     if proj_in and ll_in:
-        grass.fatal(_("Choose only one input parameter method"))
+        gcore.fatal(_("Choose only one input parameter method"))
 
     if proj_out and ll_out:
-        grass.fatal(_("Choose only one output parameter method"))
+        gcore.fatal(_("Choose only one output parameter method"))
 
     if ll_in and ll_out:
-        grass.fatal(_("Choise only one auto-projection parameter method"))
+        gcore.fatal(_("Choise only one auto-projection parameter method"))
 
-    if output and not grass.overwrite() and os.path.exists(output):
-        grass.fatal(_("Output file already exists"))
+    if output and not gcore.overwrite() and os.path.exists(output):
+        gcore.fatal(_("Output file already exists"))
 
     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:
-        grass.fatal(_(
+        gcore.fatal(_(
             "Options <coordinates> and <input> are mutually exclusive"))
 
     # parse field separator
@@ -169,59 +170,59 @@
     ofs = separator(ofs)
 
     # set up projection params
-    s = grass.read_command("g.proj", flags='j')
+    s = gcore.read_command("g.proj", flags='j')
     kv = parse_key_val(s)
     if "XY location" in kv['+proj'] and (ll_in or ll_out):
-        grass.fatal(_("Unable to project to or from a XY location"))
+        gcore.fatal(_("Unable to project to or from a XY location"))
 
     in_proj = None
 
     if ll_in:
         in_proj = "+proj=longlat +datum=WGS84"
-        grass.verbose(
+        gcore.verbose(
             "Assuming LL WGS84 as input, current projection as output ")
 
     if ll_out:
-        in_proj = grass.read_command('g.proj', flags='jf')
+        in_proj = gcore.read_command('g.proj', flags='jf')
 
     if proj_in:
         if '+' in proj_in:
             in_proj = proj_in
         else:
-            grass.fatal(_("Invalid PROJ.4 input specification"))
+            gcore.fatal(_("Invalid PROJ.4 input specification"))
 
     if not in_proj:
-        grass.verbose("Assuming current location as input")
-        in_proj = grass.read_command('g.proj', flags='jf')
+        gcore.verbose("Assuming current location as input")
+        in_proj = gcore.read_command('g.proj', flags='jf')
 
     in_proj = in_proj.strip()
-    grass.verbose("Input parameters: '%s'" % in_proj)
+    gcore.verbose("Input parameters: '%s'" % in_proj)
 
     out_proj = None
 
     if ll_out:
         out_proj = "+proj=longlat +datum=WGS84"
-        grass.verbose(
+        gcore.verbose(
             "Assuming current projection as input, LL WGS84 as output ")
 
     if ll_in:
-        out_proj = grass.read_command('g.proj', flags='jf')
+        out_proj = gcore.read_command('g.proj', flags='jf')
 
     if proj_out:
         if '+' in proj_out:
             out_proj = proj_out
         else:
-            grass.fatal(_("Invalid PROJ.4 output specification"))
+            gcore.fatal(_("Invalid PROJ.4 output specification"))
 
     if not out_proj:
-        grass.fatal(_("Missing output projection parameters "))
+        gcore.fatal(_("Missing output projection parameters "))
     out_proj = out_proj.strip()
-    grass.verbose("Output parameters: '%s'" % out_proj)
+    gcore.verbose("Output parameters: '%s'" % out_proj)
 
     # set up input file
     if coords:
         x, y = coords.split(',')
-        tmpfile = grass.tempfile()
+        tmpfile = gcore.tempfile()
         fd = open(tmpfile, "w")
         fd.write("%s%s%s\n" % (x, ifs, y))
         fd.close()
@@ -233,9 +234,9 @@
         else:
             infile = input
             if not os.path.exists(infile):
-                grass.fatal(_("Unable to read input data"))
+                gcore.fatal(_("Unable to read input data"))
             inf = file(infile)
-            grass.debug("input file=[%s]" % infile)
+            gcore.debug("input file=[%s]" % infile)
 
     # set up output file
     if not output:
@@ -244,7 +245,7 @@
     else:
         outfile = output
         outf = open(outfile, 'w')
-        grass.debug("output file=[%s]" % outfile)
+        gcore.debug("output file=[%s]" % outfile)
 
     # set up output style
     if not decimal:
@@ -263,7 +264,7 @@
     cmd = ['cs2cs'] + copyinp + outfmt + \
         in_proj.split() + ['+to'] + out_proj.split()
 
-    p = grass.Popen(cmd, stdin=grass.PIPE, stdout=grass.PIPE)
+    p = gcore.Popen(cmd, stdin=gcore.PIPE, stdout=gcore.PIPE)
 
     tr = TrThread(ifs, inf, p.stdin)
     tr.start()
@@ -276,7 +277,7 @@
                 xy, z = line.split(' ', 1)
                 x, y = xy.split('\t')
             except ValueError:
-                grass.fatal(line)
+                gcore.fatal(line)
 
             outf.write('%s%s%s%s%s\n' %
                        (x.strip(), ofs, y.strip(), ofs, z.strip()))
@@ -294,9 +295,9 @@
     p.wait()
 
     if p.returncode != 0:
-        grass.warning(_(
+        gcore.warning(_(
             "Projection transform probably failed, please investigate"))
 
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gcore.parser()
     main()

Modified: grass/trunk/scripts/r.blend/r.blend.py
===================================================================
--- grass/trunk/scripts/r.blend/r.blend.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/r.blend/r.blend.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -40,28 +40,27 @@
 #%end
 #% flag
 #% 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
 
-
-import sys
 import os
 import string
-import grass.script as grass
+import grass.script as gscript
 
+
 def main():
     first = options['first']
     second = options['second']
     output = options['output']
     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)
     perc_inv = 100.0 - percent
@@ -69,47 +68,54 @@
     frac1 = percent / 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)
 
-    grass.mapcalc(cmd,
-		  output = output,
-		  first = first, second = second,
-		  frac1 = frac1, frac2 = frac2)
+    gscript.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'])
+    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']:
-        grass.run_command('r.composite', r = '%s.r' % output,
-	    g = '%s.g' % output, b = '%s.b' % output, output = output)
+        gscript.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.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:
-        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__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     main()

Modified: grass/trunk/scripts/r.buffer.lowmem/r.buffer.lowmem.py
===================================================================
--- grass/trunk/scripts/r.buffer.lowmem/r.buffer.lowmem.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/r.buffer.lowmem/r.buffer.lowmem.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -53,15 +53,18 @@
     'feet': 0.3048,
     'miles': 1609.344,
     'nautmiles': 1852.0
-    }
+}
 
 # what to do in case of user break:
+
+
 def cleanup():
     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']:
-        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():
     global temp_dist, temp_src
 
@@ -75,13 +78,13 @@
     temp_dist = "r.buffer.tmp.%s.dist" % 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']:
         grass.fatal(_("Raster map <%s> not found") % input)
 
     scale = scales[units]
 
-    distances  = distances.split(',')
+    distances = distances.split(',')
     distances1 = [scale * float(d) for d in distances]
     distances2 = [d * d for d in distances1]
 
@@ -92,8 +95,8 @@
     else:
         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:
         exp = "$temp_src = if($input == 0,null(),1)"
@@ -101,22 +104,22 @@
         exp = "$temp_src = if(isnull($input),null(),1)"
 
     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)"
     if metric == 'squared':
         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:
         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()"
 
     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")
     d0 = "0"
     for n, d in enumerate(distances):
@@ -125,11 +128,11 @@
     p.stdin.close()
     p.wait()
 
-    grass.run_command('r.colors', map = output, color = 'rainbow')
+    grass.run_command('r.colors', map=output, color='rainbow')
 
     # write cmd history:
     grass.raster_history(output)
-    
+
 if __name__ == "__main__":
     options, flags = grass.parser()
     atexit.register(cleanup)

Modified: grass/trunk/scripts/r.colors.stddev/r.colors.stddev.py
===================================================================
--- grass/trunk/scripts/r.colors.stddev/r.colors.stddev.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/r.colors.stddev/r.colors.stddev.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -30,19 +30,22 @@
 #% description: Force center at zero
 #%end
 
-import sys
 import os
 import atexit
-import grass.script as grass
 
+import grass.script as gscript
+
+
 def z(n):
     return mean + n * stddev
 
+
 def cleanup():
     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():
     global tmpmap
     tmpmap = None
@@ -52,90 +55,89 @@
     bands = flags['b']
 
     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'])
+        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
+        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
+            # 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"])
+            # >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:
-	tmpmap = "r_col_stdev_abs_%d" % os.getpid()
-	grass.mapcalc("$tmp = abs($map)", tmp = tmpmap, map = map)
+        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 = grass.raster_info(tmpmap)
-	maxv = info['max']
+        # 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 = grass.read_command('r.univar', flags = 'eg', map = map, percentile = [95.45,68.2689,99.7300])
-	kv = grass.parse_key_val(s)
+        # 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'])
+        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
+        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,
-		])
+            # >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)
+    gscript.write_command('r.colors', map=map, rules='-', stdin=rules)
 
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     atexit.register(cleanup)
     main()

Modified: grass/trunk/scripts/r.fillnulls/r.fillnulls.py
===================================================================
--- grass/trunk/scripts/r.fillnulls/r.fillnulls.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/r.fillnulls/r.fillnulls.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -109,16 +109,19 @@
 mapset = None
 
 # what to do in case of user break:
+
+
 def cleanup():
-    #delete internal mask and any TMP files:
+    # delete internal mask and any TMP files:
     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:
-        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 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():
     global usermask, mapset, tmp_rmaps, tmp_vmaps
 
@@ -131,14 +134,18 @@
     segmax = int(options['segmax'])
     npmin = int(options['npmin'])
     lambda_ = float(options['lambda'])
+<<<<<<< 1ca5ade0f050cc22722fdcbb57af91135215607e
     quiet = True # FIXME
 
+=======
+    quiet = True  # FIXME
+>>>>>>> scripts modules: support python3
     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
-    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']:
         grass.fatal(_("Raster map <%s> not found") % input)
 
@@ -148,19 +155,19 @@
     # check if a MASK is already present
     # and remove it to not interfere with NULL lookup part
     # 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
         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':
         # idea: filter all NULLS and grow that area(s) by 3 pixel, then
         # interpolate from these surrounding 3 pixel edge
         filling = prefix + 'filled'
 
         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()
         ns_res = region['nsres']
         ew_res = region['ewres']
@@ -172,10 +179,10 @@
         if usermask:
             grass.message(_("Skipping masked raster parts"))
             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:
             grass.mapcalc("$tmp1 = if(isnull($input),1,null())",
-                tmp1 = prefix + 'nulls', input = input)
+                          tmp1=prefix + 'nulls', input=input)
         tmp_rmaps.append(prefix + 'nulls')
 
         # restoring user's mask, if present
@@ -183,7 +190,7 @@
         if usermask:
             grass.message(_("Restoring user mask (MASK)..."))
             try:
-                grass.run_command('g.rename', quiet=quiet, raster = (usermask, 'MASK'))
+                grass.run_command('g.rename', quiet=quiet, raster=(usermask, 'MASK'))
             except CalledModuleError:
                 grass.warning(_("Failed to restore user MASK!"))
             usermask = None
@@ -196,19 +203,27 @@
                               radius=edge + 0.01, old=1, new=1,
                               out=prefix + 'grown', quiet=quiet)
         except CalledModuleError:
-            grass.fatal(_("abandoned. Removing temporary map, restoring user mask if needed:"))
+            grass.fatal(_("abandoned. Removing temporary map, restoring "
+                          "user mask if needed:"))
 
         # assign unique IDs to each hole or hole system (holes closer than edge distance)
         grass.message(_("Assigning IDs to NULL areas"))
         tmp_rmaps.append(prefix + 'clumped')
         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:
-            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
         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')
 
         # use new IDs to identify holes
@@ -217,12 +232,19 @@
                               input=prefix + 'holes', output=prefix + 'holes',
                               type='area', quiet=quiet)
         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')
 
         # get a list of unique hole cat's
         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()
         cats_file = file(cats_file_name)
         for line in cats_file:
@@ -248,17 +270,19 @@
                                   output=holename + '_pol',
                                   cats=cat, quiet=quiet)
             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')
 
-            # 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:
                 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),
+                                  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)
             except CalledModuleError:
                 grass.fatal(_("abandoned. Removing temporary maps, restoring "
@@ -269,12 +293,13 @@
                 grass.run_command('g.remove', flags='fb', type='vector',
                                   name=holename + '_pol', quiet=quiet)
             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')
 
             # copy only data around hole
             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)
 
             # If here loop is split into two, next part of loop can be run in parallel
@@ -285,13 +310,14 @@
             tmp_rmaps.append(holename + '_grown')
             try:
                 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:
-                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
             grass.mapcalc("$out = if($inp == -1, null(), $dem)",
-                            out = holename + '_edges', inp = holename + '_grown', dem = input)
+                          out=holename + '_edges', inp=holename + '_grown', dem=input)
             tmp_rmaps.append(holename + '_edges')
 
             # convert to points for interpolation
@@ -301,10 +327,11 @@
                                   input=holename + '_edges', output=holename,
                                   type='point', flags='z', quiet=quiet)
             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:
-            pointsnumber = grass.vector_info_topo(map = holename)['points']
+            pointsnumber = grass.vector_info_topo(map=holename)['points']
             grass.verbose(_("Interpolating %d points") % pointsnumber)
 
             if pointsnumber < 2:
@@ -339,29 +366,41 @@
                     tmp_vmaps.remove(holename)
                 except:
                     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)
                 continue
 
             # append hole result to interpolated version later used to patch into original DEM
             if first:
                 tmp_rmaps.append(filling)
-                grass.run_command('g.region', align = input, raster = holename + '_dem', quiet = quiet)
+                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')
+                              out=filling, inp=holename, dem=holename + '_dem')
                 first = False
             else:
                 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:
                     grass.run_command('g.rename',
                                       raster=(filling + '_tmp', filling),
                                       overwrite=True, quiet=quiet)
                 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
             try:
@@ -379,7 +418,8 @@
                                         holename + '_edges',
                                         holename + '_dem'))
             except CalledModuleError:
-                grass.fatal(_("abandoned. Removing temporary maps, restoring user mask if needed:"))
+                grass.fatal(_("abandoned. Removing temporary maps, restoring "
+                              "user mask if needed:"))
             try:
                 tmp_vmaps.remove(holename)
             except:
@@ -390,27 +430,27 @@
             except CalledModuleError:
                 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':
         grass.message(_("Using %s bspline interpolation") % method)
 
         # clone current region
         grass.use_temp_region()
-        grass.run_command('g.region', align = input)
+        grass.run_command('g.region', align=input)
 
         reg = grass.region()
         # launch r.resamp.bspline
         tmp_rmaps.append(prefix + 'filled')
         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_=lambda_, 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_=lambda_, flags='n')
         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_=lambda_, 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_=lambda_, flags='n')
 
     # restoring user's mask, if present:
     if usermask:
@@ -422,13 +462,14 @@
         usermask = None
 
     # 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
     grass.message(_("Patching fill data into NULL areas..."))
     # 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
     grass.del_temp_region()
@@ -439,7 +480,9 @@
     grass.raster_history(output)
 
     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]
         for hole in failed_list[1:]:
             outlist = ', ' + outlist

Modified: grass/trunk/scripts/r.grow/r.grow.py
===================================================================
--- grass/trunk/scripts/r.grow/r.grow.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/r.grow/r.grow.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -72,9 +72,10 @@
 def cleanup():
     for map in [temp_dist, temp_val]:
         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():
     global temp_dist, temp_val
 
@@ -108,7 +109,7 @@
         metric = 'squared'
         radius = radius * radius
 
-    #check if input file exists
+    # check if input file exists
     if not grass.find_file(input)['file']:
         grass.fatal(_("Raster map <%s> not found") % input)
 
@@ -120,10 +121,10 @@
 
     grass.mapcalc(
         "$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:
     grass.raster_history(output)

Modified: grass/trunk/scripts/r.import/r.import.py
===================================================================
--- grass/trunk/scripts/r.import/r.import.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/r.import/r.import.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -161,7 +161,8 @@
         if tgtres_value <= 0:
             grass.fatal(_("Resolution value can't be smaller than 0"))
     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()
     tgtloc = grassenv['LOCATION_NAME']
@@ -211,14 +212,18 @@
             parameters['band'] = bands
         try:
             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
         except CalledModuleError as e:
             grass.fatal(_("Unable to import GDAL dataset <%s>") % GDALdatasource)
-    
+
     # make sure target is not xy
     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
     os.environ['GISRC'] = str(SRCGISRC)
@@ -327,7 +332,9 @@
         grass.run_command('g.remove', type='vector', name=vreg,
                           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']:
             continue
 
@@ -340,7 +347,9 @@
             res = estres
         elif 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
             grass.run_command('g.region', res=res, flags='a')
         else:

Modified: grass/trunk/scripts/r.in.aster/r.in.aster.py
===================================================================
--- grass/trunk/scripts/r.in.aster/r.in.aster.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/r.in.aster/r.in.aster.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -5,9 +5,9 @@
 # MODULE:    r_in_aster.py
 # AUTHOR(S): Michael Barton (michael.barton at asu.edu) and
 #               Glynn Clements (glynn at 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
-# PURPOSE:   Rectifies, georeferences, & imports Terra-ASTER imagery 
+# PURPOSE:   Rectifies, georeferences, & imports Terra-ASTER imagery
 #               using gdalwarp
 # COPYRIGHT: (C) 2008 by the GRASS Development Team
 #
@@ -57,16 +57,16 @@
 
 bands = {
     'L1A': {
-        '1':  "VNIR_Band1:ImageData",
-        '2':  "VNIR_Band2:ImageData",
+        '1': "VNIR_Band1:ImageData",
+        '2': "VNIR_Band2:ImageData",
         '3n': "VNIR_Band3N: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",
         '11': "TIR_Band11:ImageData",
         '12': "TIR_Band12:ImageData",
@@ -74,16 +74,16 @@
         '14': "TIR_Band14:ImageData"
     },
     'L1B': {
-        '1':  "VNIR_Swath:ImageData1",
-        '2':  "VNIR_Swath:ImageData2",
+        '1': "VNIR_Swath:ImageData1",
+        '2': "VNIR_Swath:ImageData2",
         '3n': "VNIR_Swath:ImageData3N",
         '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",
         '11': "TIR_Swath:ImageData11",
         '12': "TIR_Swath:ImageData12",
@@ -92,35 +92,35 @@
     }
 }
 
+
 def main():
     input = options['input']
     proctype = options['proctype']
     output = options['output']
     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'):
         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:
-      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':
         bandlist = allbands
     else:
         bandlist = band.split(',')
 
-    #initialize datasets for L1A and L1B
+    # initialize datasets for L1A and L1B
     if proctype in ["L1A", "L1B"]:
         for band in bandlist:
             if band in allbands:
@@ -129,36 +129,37 @@
                 import_aster(proj, srcfile, tempfile, band)
             else:
                 grass.fatal(_('band %s is not an available Terra/ASTER band') % band)
-    elif proctype == "DEM": 
+    elif proctype == "DEM":
         srcfile = input
         import_aster(proj, srcfile, tempfile, "DEM")
 
-    #cleanup
+    # cleanup
     grass.message(_("Cleaning up ..."))
     grass.try_remove(tempfile)
     grass.message(_("Done."))
 
     return
 
+
 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.debug("gdalwarp -t_srs %s %s %s" % (proj, srcfile, tempfile))
 
     if platform.system() == "Darwin":
-        cmd = ["arch", "-i386", "gdalwarp", "-t_srs", proj, srcfile, tempfile ]
+        cmd = ["arch", "-i386", "gdalwarp", "-t_srs", proj, srcfile, tempfile]
     else:
-        cmd = ["gdalwarp", "-t_srs", proj, srcfile, tempfile ]
+        cmd = ["gdalwarp", "-t_srs", proj, srcfile, tempfile]
     p = grass.call(cmd)
     if p != 0:
-        #check to see if gdalwarp executed properly
+        # check to see if gdalwarp executed properly
         return
 
-    #import geotiff to GRASS
+    # import geotiff to GRASS
     grass.message(_("Importing into GRASS ..."))
     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
     grass.raster_history(outfile)

Modified: grass/trunk/scripts/r.in.srtm/r.in.srtm.py
===================================================================
--- grass/trunk/scripts/r.in.srtm/r.in.srtm.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/r.in.srtm/r.in.srtm.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -19,18 +19,18 @@
 # Aug 2004: modified to accept files from other directories
 #           (by 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
 # 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
 #     (note: document was updated silently end of 2003)
 #
 # ftp://e0srp01u.ecs.nasa.gov/srtm/version1/Documentation/SRTM_Topo.txt
 #  "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
 #  30 meters in extent."
 #
@@ -40,7 +40,7 @@
 #
 #- BIL uses *center* of the UL (!) pixel:
 #      http://downloads.esri.com/support/whitepapers/other_/eximgav.pdf
-#  
+#
 #- GDAL uses *corners* of pixels for its coordinates.
 #
 # NOTE: Even, if small difference: SRTM is referenced to EGM96, not WGS84 ellps
@@ -116,12 +116,13 @@
 
 def cleanup():
     if not in_temp:
-	return
+        return
     for ext in ['.bil', '.hdr', '.prj', '.hgt.zip']:
-	grass.try_remove(tile + ext)
+        grass.try_remove(tile + ext)
     os.chdir('..')
     grass.try_rmdir(tmpdir)
 
+
 def main():
     global tile, tmpdir, in_temp
 
@@ -131,55 +132,55 @@
     output = options['output']
     one = flags['1']
 
-    #are we in LatLong location?
+    # are we in LatLong location?
     s = grass.read_command("g.proj", flags='j')
     kv = grass.parse_key_val(s)
     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:
     infile = input
     while infile[-4:].lower() in ['.hgt', '.zip']:
-	infile = infile[:-4]
+        infile = infile[:-4]
     (fdir, tile) = os.path.split(infile)
 
     if not output:
-	tileout = tile
+        tileout = tile
     else:
-	tileout = output
+        tileout = output
 
     zipfile = infile + ".hgt.zip"
     hgtfile = os.path.join(fdir, tile[:7] + ".hgt")
     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'))
+        # 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)
+        # 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
+        is_zip = True
     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:
-	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()
     grass.try_remove(tmpdir)
     os.mkdir(tmpdir)
 
     if is_zip:
-	shutil.copyfile(zipfile, os.path.join(tmpdir, tile + ".hgt.zip"))
+        shutil.copyfile(zipfile, os.path.join(tmpdir, tile + ".hgt.zip"))
     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)
     in_temp = True
 
@@ -188,26 +189,26 @@
     bilfile = tile + ".bil"
 
     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..."))
     os.rename(hgtfile, bilfile)
 
     north = tile[0]
-    ll_latitude  = int(tile[1:3])
+    ll_latitude = int(tile[1:3])
     east = tile[3]
     ll_longitude = int(tile[4:7])
 
     # are we on the southern hemisphere? If yes, make LATITUDE negative.
     if north == "S":
-	ll_latitude *= -1
+        ll_latitude *= -1
 
     # are we west of Greenwich? If yes, make LONGITUDE negative.
     if east == "W":
-	ll_longitude *= -1
+        ll_longitude *= -1
 
     # Calculate Upper Left from Lower Left
     ulxmap = "%.1f" % ll_longitude
@@ -215,10 +216,10 @@
     ulymap = "%.1f" % (ll_latitude + 1)
 
     if not one:
-	tmpl = tmpl3sec
+        tmpl = tmpl3sec
     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)
     hdrfile = tile + '.hdr'
@@ -226,7 +227,7 @@
     outf.write(header)
     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'
     outf = file(prjfile, 'w')
     outf.write(proj)
@@ -238,7 +239,7 @@
         grass.fatal(_("Unable to import data"))
 
     # nice color table
-    grass.run_command('r.colors', map = tileout, color = 'srtm')
+    grass.run_command('r.colors', map=tileout, color='srtm')
 
     # write cmd history:
     grass.raster_history(tileout)

Modified: grass/trunk/scripts/r.in.wms/r.in.wms.py
===================================================================
--- grass/trunk/scripts/r.in.wms/r.in.wms.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/r.in.wms/r.in.wms.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -58,8 +58,8 @@
 #%option
 #% key: srs
 #% type: integer
-#% description: EPSG code of requested source projection 
-#% answer:4326 
+#% description: EPSG code of requested source projection
+#% answer:4326
 #% guisection: Request
 #%end
 
@@ -178,29 +178,31 @@
 
 import grass.script as grass
 
+
 def GetRegionParams(opt_region):
 
-    # set region 
+    # set region
     if opt_region:
         reg_spl = opt_region.strip().split('@', 1)
         reg_mapset = '.'
         if len(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:
         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:
         region_params = grass.region()
 
     return region_params
 
+
 def main():
 
     if 'GRASS' in options['driver']:
@@ -211,7 +213,7 @@
         grass.debug("Using GDAL WMS driver")
         from wms_gdal_drv import WMSGdalDrv
         wms = WMSGdalDrv()
-    
+
     if flags['c']:
         wms.GetCapabilities(options)
     else:

Modified: grass/trunk/scripts/r.in.wms/srs.py
===================================================================
--- grass/trunk/scripts/r.in.wms/srs.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/r.in.wms/srs.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -1,5 +1,5 @@
 """!
- at brief WMS, WMTS and NASA OnEarth drivers implemented in GRASS using GDAL Python bindings. 
+ at brief WMS, WMTS and NASA OnEarth drivers implemented in GRASS using GDAL Python bindings.
 
 List of classes:
  - srs.py::Srs
@@ -32,6 +32,7 @@
           * urn:ogc:def:crs:EPSG:4326
         :param string axisorder: Force / override axisorder ('xy' or 'yx')
     """
+
     def __init__(self, srs):
         self.id = srs
         self.naming_authority = None
@@ -45,7 +46,7 @@
 
         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"
             vals = self.id.split('/')
             self.authority = vals[5].upper()
@@ -84,7 +85,7 @@
             self.code = int(values[1])
 
         if self.code in axisorder_yx:
-                self.axisorder = 'yx'
+            self.axisorder = 'yx'
 
     def getcode(self):
         """Create for example "EPSG:4326" string and return back
@@ -101,10 +102,10 @@
         """
 
         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([
     4326,

Modified: grass/trunk/scripts/r.in.wms/wms_base.py
===================================================================
--- grass/trunk/scripts/r.in.wms/wms_base.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/r.in.wms/wms_base.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -33,12 +33,13 @@
 
 
 class WMSBase:
+
     def __init__(self):
         # these variables are information for destructor
         self.temp_files_to_cleanup = []
 
         self.params = {}
-        self.tile_size = {'bbox' : None}
+        self.tile_size = {'bbox': None}
 
         self.temp_map = None
         self.temp_warpmap = None
@@ -81,31 +82,34 @@
             self.params[key] = options[key]
 
         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()
 
         if options['format'] == "jpeg" and \
            not 'format' in driver_props['ignored_params']:
             if not flags['o'] and \
-              'WMS' in self.params['driver']:
+                    'WMS' in self.params['driver']:
                 grass.warning(_("JPEG format does not support transparency"))
 
         self.params['format'] = drv_info.GetFormat(options['format'])
         if not 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'])
-        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'])
 
         self.params['wms_version'] = options['wms_version']
         if "CRS" in GetSRSParamVal(self.params['srs']) and self.params['wms_version'] == "1.1.1":
             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":
             self.params['proj_name'] = "CRS"
@@ -114,7 +118,7 @@
 
         # read projection info
         self.proj_location = grass.read_command('g.proj',
-                                                flags ='jf').rstrip('\n')
+                                                flags='jf').rstrip('\n')
         self.proj_location = self._modifyProj(self.proj_location)
 
         if self.params['srs'] in [3857, 900913]:
@@ -124,8 +128,8 @@
             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:
             self.proj_srs = grass.read_command('g.proj',
-                                               flags = 'jf',
-                                               epsg = str(GetEpsg(self.params['srs']))).rstrip('\n')
+                                               flags='jf',
+                                               epsg=str(GetEpsg(self.params['srs']))).rstrip('\n')
 
         self.proj_srs = self._modifyProj(self.proj_srs)
 
@@ -143,9 +147,18 @@
         if maxrows <= min_tile_size:
             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
         self.gdal_drv_format = "GTiff"
@@ -167,34 +180,33 @@
         not_relevant_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 \
-               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:
             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'])))
 
         not_relevant_flags = []
         for i_flag in driver_props['ignored_flags']:
 
             if flags[i_flag]:
-                not_relevant_flags.append('<' + i_flag  + '>')
+                not_relevant_flags.append('<' + i_flag + '>')
 
         if len(not_relevant_flags) > 0:
             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'])))
 
     def GetMap(self, options, flags):
         """!Download data from WMS server."""
 
         self._initializeParameters(options, flags)
+        self.bbox = self._computeBbox()
 
-        self.bbox     = self._computeBbox()
-
         self.temp_map = self._download()
 
         if not self.temp_map:
@@ -244,13 +256,13 @@
         grass.debug('Fetching capabilities OK')
         return cap
 
-    def _fetchDataFromServer(self, url, username = None, password = None):
+    def _fetchDataFromServer(self, url, username=None, password=None):
         """!Fetch data from server
         """
         request = Request(url)
         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:
             return urlopen(request)
@@ -260,7 +272,7 @@
     def GetCapabilities(self, options):
         """!Get capabilities from WMS server
         """
-        cap  = self._fetchCapabilities(options)
+        cap = self._fetchCapabilities(options)
         capfile_output = options['capfile_output'].strip()
 
         # save to file
@@ -283,7 +295,7 @@
         """
         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 = {}
 
         if self.proj_srs == self.proj_location:  # TODO: do it better
@@ -302,21 +314,21 @@
 
             try:
                 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:
-                 grass.fatal(_("Unable to write data into tempfile"))
+                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
+            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)
             if not points:
                 grass.fatal(_("Unable to determine region, %s failed") % 'm.proj')
@@ -337,12 +349,12 @@
                     bbox['minx'] = point[0]
                     continue
 
-                if   bbox['maxy'] < point[1]:
+                if bbox['maxy'] < point[1]:
                     bbox['maxy'] = point[1]
                 elif bbox['miny'] > point[1]:
                     bbox['miny'] = point[1]
 
-                if   bbox['maxx'] < point[0]:
+                if bbox['maxx'] < point[0]:
                     bbox['maxx'] = point[0]
                 elif bbox['minx'] > point[0]:
                     bbox['minx'] = point[0]
@@ -359,7 +371,7 @@
         """!Reproject data  using gdalwarp if needed
         """
         # 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..."))
             self.temp_warpmap = grass.tempfile()
 
@@ -383,14 +395,14 @@
                                       '-s_srs', '%s' % self.proj_srs,
                                       '-t_srs', '%s' % self.proj_location,
                                       '-r', gdal_method, '-dstalpha',
-                                      self.temp_map, self.temp_warpmap], stdout = nuldev)
+                                      self.temp_map, self.temp_warpmap], stdout=nuldev)
                 # RGBA rasters
                 else:
                     ps = grass.Popen(['gdalwarp',
                                       '-s_srs', '%s' % self.proj_srs,
                                       '-t_srs', '%s' % self.proj_location,
                                       '-r', gdal_method,
-                                      self.temp_map, self.temp_warpmap], stdout = nuldev)
+                                      self.temp_map, self.temp_warpmap], stdout=nuldev)
                 ps.wait()
             except OSError as e:
                 grass.fatal('%s \nThis can be caused by missing %s utility. ' % (e, 'gdalwarp'))
@@ -423,10 +435,12 @@
 
         return temp_file
 
+
 class GRASSImporter:
+
     def __init__(self, opt_output):
 
-        self.cleanup_mask   = False
+        self.cleanup_mask = False
         self.cleanup_layers = False
 
         # output map name
@@ -438,9 +452,9 @@
 
         # check names of temporary rasters, which module may create
         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
-            if grass.find_file(rast, element = 'cell', mapset = '.')['file']:
+            if grass.find_file(rast, element='cell', mapset='.')['file']:
                 maps.append(rast)
 
         if len(maps) != 0:
@@ -457,7 +471,8 @@
                 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']:
+            if grass.find_file(self.opt_output + self.original_mask_suffix,
+                               element='cell', mapset='.')['name']:
                 try:
                     mask_copy = self.opt_output + self.original_mask_suffix
                     grass.run_command('g.copy', quiet=True,
@@ -470,15 +485,15 @@
             maps = []
             for suffix in ('.red', '.green', '.blue', '.alpha', self.original_mask_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)
 
             if maps:
                 grass.run_command('g.remove',
-                                  quiet = True,
-                                  flags = 'fb',
-                                  type = 'raster',
-                                  name = ','.join(maps))
+                                  quiet=True,
+                                  flags='fb',
+                                  type='raster',
+                                  name=','.join(maps))
 
         # delete environmental variable which overrides region
         if 'GRASS_REGION' in os.environ.keys():
@@ -500,18 +515,18 @@
         self.cleanup_layers = True
 
         # 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'
         else:
             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
         # of warped layer (may not be a rectangle), also mask contains
         # 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
-            if grass.find_file('MASK', element = 'cell', mapset = '.' )['name']:
+            if grass.find_file('MASK', element='cell', mapset='.')['name']:
                 try:
                     mask_copy = self.opt_output + self.original_mask_suffix
                     grass.run_command('g.copy', quiet=True,
@@ -530,8 +545,8 @@
             except CalledModuleError:
                 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:
                 grass.run_command('r.composite',
                                   quiet=True, overwrite=True,
@@ -544,7 +559,9 @@
 
         grass.message(_('<%s> created.') % self.opt_output)
 
+
 class WMSDriversInfo:
+
     def __init__(self):
         """!Provides information about driver parameters.
         """
@@ -553,11 +570,16 @@
         self.f_labels = ["geotiff", "tiff", "png", "jpeg", "gif", "png8"]
 
         # 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")
 
-
     def GetDrvProperties(self, driver):
         """!Get information about driver parameters.
         """
@@ -570,7 +592,6 @@
         if 'OnEarth' in driver:
             return self._OnEarthProperties()
 
-
     def _OnEarthProperties(self):
 
         props = {}
@@ -604,7 +625,7 @@
         props = {}
         props['ignored_flags'] = []
         props['ignored_params'] = ['urlparams', 'bgcolor', 'capfile', 'capfile_output',
-                                    'username', 'password']
+                                   'username', 'password']
         props['req_multiple_layers'] = True
 
         return props
@@ -631,8 +652,7 @@
         return self.srs
 
 
-
-#TODO move to utils?
+# TODO move to utils?
 def GetSRSParamVal(srs):
     """!Decides whether to use CRS or EPSG prefix according to srs number.
     """
@@ -642,6 +662,7 @@
     else:
         return "EPSG:%d" % srs
 
+
 def GetEpsg(srs):
     """
      @return EPSG number

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

Modified: grass/trunk/scripts/r.in.wms/wms_drv.py
===================================================================
--- grass/trunk/scripts/r.in.wms/wms_drv.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/r.in.wms/wms_drv.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -1,5 +1,5 @@
 """!
- at brief WMS, WMTS and NASA OnEarth drivers implemented in GRASS using GDAL Python bindings. 
+ at brief WMS, WMTS and NASA OnEarth drivers implemented in GRASS using GDAL Python bindings.
 
 List of classes:
  - wms_drv::WMSDrv
@@ -17,13 +17,13 @@
 """
 
 import socket
-import grass.script as grass 
+import grass.script as grass
 
-from time      import sleep
+from time import sleep
 
 try:
     from osgeo import gdal
-    from osgeo import gdalconst 
+    from osgeo import gdalconst
 except:
     grass.fatal(_("Unable to load GDAL python bindings"))
 
@@ -41,20 +41,22 @@
 
 try:
     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 wms_base import WMSBase, GetSRSParamVal
 
 from wms_cap_parsers import WMTSCapabilitiesTree, OnEarthCapabilitiesTree
 from srs import Srs
 
+
 class WMSDrv(WMSBase):
+
     def _download(self):
         """!Downloads data from WMS server using own driver
-        
+
         @return temp_map with downloaded data
-        """ 
+        """
         grass.message(_("Downloading data from WMS server..."))
 
         if "?" in self.params["url"]:
@@ -69,13 +71,29 @@
 
         # initialize correct manager according to chosen OGC service
         if self.params['driver'] == 'WMTS_GRASS':
-            req_mgr = WMTSRequestMgr(self.params, self.bbox, self.region, self.proj_srs, self.cap_file)
+            req_mgr = WMTSRequestMgr(
+                self.params,
+                self.bbox,
+                self.region,
+                self.proj_srs,
+                self.cap_file)
         elif self.params['driver'] == 'WMS_GRASS':
-            req_mgr = WMSRequestMgr(self.params, self.bbox, self.region, self.tile_size, self.proj_srs)
+            req_mgr = WMSRequestMgr(
+                self.params,
+                self.bbox,
+                self.region,
+                self.tile_size,
+                self.proj_srs)
         elif self.params['driver'] == 'OnEarth_GRASS':
-            req_mgr = OnEarthRequestMgr(self.params, self.bbox, self.region, self.proj_srs, self.cap_file)
+            req_mgr = OnEarthRequestMgr(
+                self.params,
+                self.bbox,
+                self.region,
+                self.proj_srs,
+                self.cap_file)
 
-        # get information about size in pixels and bounding box of raster, where all tiles will be joined
+        # get information about size in pixels and bounding box of raster, where
+        # all tiles will be joined
         map_region = req_mgr.GetMapRegion()
 
         init = True
@@ -87,10 +105,11 @@
         while True:
 
             if fetch_try == 0:
-                # get url for request the tile and information for placing the tile into raster with other tiles
+                # get url for request the tile and information for placing the tile into
+                # raster with other tiles
                 tile = req_mgr.GetNextTile()
 
-            # if last tile has been already downloaded 
+            # if last tile has been already downloaded
             if not tile:
                 break
 
@@ -100,16 +119,22 @@
             # the tile size and offset in pixels for placing it into raster where tiles are joined
             tile_ref = tile[1]
             grass.debug(query_url, 2)
-            try: 
-                wms_data = self._fetchDataFromServer(query_url, self.params['username'], self.params['password'])
+            try:
+                wms_data = self._fetchDataFromServer(
+                    query_url, self.params['username'],
+                    self.params['password'])
             except (IOError, HTTPException) as e:
-                if HTTPError == type(e) and e.code == 401:
-                    grass.fatal(_("Authorization failed to '%s' when fetching data.\n%s") % (self.params['url'], str(e)))
+                if isinstance(e, HTTPError) and e.code == 401:
+                    grass.fatal(
+                        _("Authorization failed to '%s' when fetching data.\n%s") %
+                        (self.params['url'], str(e)))
                 else:
-                    grass.fatal(_("Unable to fetch data from: '%s'\n%s") % (self.params['url'], str(e)))
+                    grass.fatal(
+                        _("Unable to fetch data from: '%s'\n%s") %
+                        (self.params['url'], str(e)))
 
             temp_tile = self._tempfile()
-                
+
             # download data into temporary file
             try:
                 temp_tile_opened = open(temp_tile, 'wb')
@@ -117,8 +142,9 @@
             except IOError as e:
                 # some servers are not happy with many subsequent requests for tiles done immediately,
                 # if immediate request was unsuccessful, try to repeat the request after 5s and 30s breaks
-                # TODO probably servers can return more kinds of errors related to this problem (not only 104)
-                if socket.error == type(e) and e[0] == 104 and fetch_try < 2:
+                # TODO probably servers can return more kinds of errors related to this
+                # problem (not only 104)
+                if isinstance(e, socket.error) and e[0] == 104 and fetch_try < 2:
                     fetch_try += 1
 
                     if fetch_try == 1:
@@ -126,7 +152,9 @@
                     elif fetch_try == 2:
                         sleep_time = 30
 
-                    grass.warning(_("Server refused to send data for a tile.\nRequest will be repeated after %d s.") % sleep_time)
+                    grass.warning(
+                        _("Server refused to send data for a tile.\nRequest will be repeated after %d s.") %
+                        sleep_time)
 
                     sleep(sleep_time)
                     continue
@@ -136,226 +164,250 @@
                 temp_tile_opened.close()
 
             fetch_try = 0
-                
-            tile_dataset_info = gdal.Open(temp_tile, gdal.GA_ReadOnly) 
+
+            tile_dataset_info = gdal.Open(temp_tile, gdal.GA_ReadOnly)
             if tile_dataset_info is None:
                 # print error xml returned from server
                 try:
                     error_xml_opened = open(temp_tile, 'rb')
-                    err_str = error_xml_opened.read()     
+                    err_str = error_xml_opened.read()
                 except IOError as e:
                     grass.fatal(_("Unable to read data from tempfile.\n%s") % str(e))
                 finally:
                     error_xml_opened.close()
 
-                if  err_str is not None:
-                    grass.fatal(_("WMS server error: %s") %  err_str)
+                if err_str is not None:
+                    grass.fatal(_("WMS server error: %s") % err_str)
                 else:
-                    grass.fatal(_("WMS server unknown error") )
-                
+                    grass.fatal(_("WMS server unknown error"))
+
             temp_tile_pct2rgb = None
             if tile_dataset_info.RasterCount == 1 and \
                tile_dataset_info.GetRasterBand(1).GetRasterColorTable() is not None:
-                # expansion of color table into bands 
+                # expansion of color table into bands
                 temp_tile_pct2rgb = self._tempfile()
                 tile_dataset = self._pct2rgb(temp_tile, temp_tile_pct2rgb)
-            else: 
+            else:
                 tile_dataset = tile_dataset_info
-                
+
             # initialization of temp_map_dataset, where all tiles are merged
             if init:
                 temp_map = self._tempfile()
-                    
+
                 driver = gdal.GetDriverByName(self.gdal_drv_format)
                 metadata = driver.GetMetadata()
-                if not metadata.has_key(gdal.DCAP_CREATE) or \
-                       metadata[gdal.DCAP_CREATE] == 'NO':
-                    grass.fatal(_('Driver %s does not supports Create() method') % drv_format)  
+                if gdal.DCAP_CREATE not in metadata or \
+                        metadata[gdal.DCAP_CREATE] == 'NO':
+                    grass.fatal(_('Driver %s does not supports Create() method') % drv_format)
                 self.temp_map_bands_num = tile_dataset.RasterCount
                 temp_map_dataset = driver.Create(temp_map, map_region['cols'], map_region['rows'],
-                                                 self.temp_map_bands_num, 
+                                                 self.temp_map_bands_num,
                                                  tile_dataset.GetRasterBand(1).DataType)
                 init = False
-                
+
             # tile is written into temp_map
             tile_to_temp_map = tile_dataset.ReadRaster(0, 0, tile_ref['sizeX'], tile_ref['sizeY'],
-                                                             tile_ref['sizeX'], tile_ref['sizeY'])
-                
+                                                       tile_ref['sizeX'], tile_ref['sizeY'])
+
             temp_map_dataset.WriteRaster(tile_ref['t_cols_offset'], tile_ref['t_rows_offset'],
-                                         tile_ref['sizeX'],  tile_ref['sizeY'], tile_to_temp_map) 
-                
+                                         tile_ref['sizeX'], tile_ref['sizeY'], tile_to_temp_map)
+
             tile_dataset = None
             tile_dataset_info = None
             grass.try_remove(temp_tile)
-            grass.try_remove(temp_tile_pct2rgb)    
+            grass.try_remove(temp_tile_pct2rgb)
 
         if not temp_map:
             return temp_map
         # georeferencing and setting projection of temp_map
-        projection = grass.read_command('g.proj', 
-                                        flags = 'wf',
-                                        epsg =self.params['srs']).rstrip('\n')
+        projection = grass.read_command('g.proj',
+                                        flags='wf',
+                                        epsg=self.params['srs']).rstrip('\n')
         temp_map_dataset.SetProjection(projection)
 
         pixel_x_length = (map_region['maxx'] - map_region['minx']) / int(map_region['cols'])
         pixel_y_length = (map_region['miny'] - map_region['maxy']) / int(map_region['rows'])
 
-        geo_transform = [map_region['minx'] , pixel_x_length  , 0.0 , map_region['maxy'] , 0.0 , pixel_y_length] 
-        temp_map_dataset.SetGeoTransform(geo_transform )
+        geo_transform = [
+            map_region['minx'],
+            pixel_x_length,
+            0.0,
+            map_region['maxy'],
+            0.0,
+            pixel_y_length]
+        temp_map_dataset.SetGeoTransform(geo_transform)
         temp_map_dataset = None
-        
+
         return temp_map
-    
+
     def _pct2rgb(self, src_filename, dst_filename):
-        """!Create new dataset with data in dst_filename with bands according to src_filename 
+        """!Create new dataset with data in dst_filename with bands according to src_filename
         raster color table - modified code from gdal utility pct2rgb
-        
+
         @return new dataset
-        """  
+        """
         out_bands = 4
         band_number = 1
-        
+
         # open source file
         src_ds = gdal.Open(src_filename)
         if src_ds is None:
             grass.fatal(_('Unable to open %s ' % src_filename))
-            
+
         src_band = src_ds.GetRasterBand(band_number)
-        
+
         # Build color table
-        lookup = [ Numeric.arrayrange(256), 
-                   Numeric.arrayrange(256), 
-                   Numeric.arrayrange(256), 
-                   Numeric.ones(256)*255 ]
-        
-        ct = src_band.GetRasterColorTable()	
+        lookup = [Numeric.arrayrange(256),
+                  Numeric.arrayrange(256),
+                  Numeric.arrayrange(256),
+                  Numeric.ones(256) * 255]
+
+        ct = src_band.GetRasterColorTable()
         if ct is not None:
-            for i in range(min(256,ct.GetCount())):
+            for i in range(min(256, ct.GetCount())):
                 entry = ct.GetColorEntry(i)
                 for c in range(4):
                     lookup[c][i] = entry[c]
-        
+
         # create the working file
         gtiff_driver = gdal.GetDriverByName(self.gdal_drv_format)
         tif_ds = gtiff_driver.Create(dst_filename,
                                      src_ds.RasterXSize, src_ds.RasterYSize, out_bands)
-        
+
         # do the processing one scanline at a time
         for iY in range(src_ds.RasterYSize):
-            src_data = src_band.ReadAsArray(0,iY,src_ds.RasterXSize,1)
-            
+            src_data = src_band.ReadAsArray(0, iY, src_ds.RasterXSize, 1)
+
             for iBand in range(out_bands):
                 band_lookup = lookup[iBand]
-                
-                dst_data = Numeric.take(band_lookup,src_data)
-                tif_ds.GetRasterBand(iBand+1).WriteArray(dst_data,0,iY)
-        
-        return tif_ds       
 
+                dst_data = Numeric.take(band_lookup, src_data)
+                tif_ds.GetRasterBand(iBand + 1).WriteArray(dst_data, 0, iY)
+
+        return tif_ds
+
+
 class BaseRequestMgr:
-    """!Base class for request managers. 
+    """!Base class for request managers.
     """
+
     def _computeRequestData(self, bbox, tl_corner, tile_span, tile_size, mat_num_bbox):
         """!Initialize data needed for iteration through tiles. Used by WMTS_GRASS and OnEarth_GRASS drivers.
-        """ 
+        """
         epsilon = 1e-15
 
-        # request data bbox specified in row and col number 
+        # request data bbox specified in row and col number
         self.t_num_bbox = {}
 
-        self.t_num_bbox['min_col'] = int(floor((bbox['minx'] - tl_corner['minx']) / tile_span['x'] + epsilon))
-        self.t_num_bbox['max_col'] = int(floor((bbox['maxx'] - tl_corner['minx']) / tile_span['x'] - epsilon))
+        self.t_num_bbox['min_col'] = int(
+            floor((bbox['minx'] - tl_corner['minx']) / tile_span['x'] + epsilon))
+        self.t_num_bbox['max_col'] = int(
+            floor((bbox['maxx'] - tl_corner['minx']) / tile_span['x'] - epsilon))
 
-        self.t_num_bbox['min_row'] = int(floor((tl_corner['maxy'] - bbox['maxy']) / tile_span['y'] + epsilon))
-        self.t_num_bbox['max_row'] = int(floor((tl_corner['maxy'] - bbox['miny']) / tile_span['y'] - epsilon))
+        self.t_num_bbox['min_row'] = int(
+            floor((tl_corner['maxy'] - bbox['maxy']) / tile_span['y'] + epsilon))
+        self.t_num_bbox['max_row'] = int(
+            floor((tl_corner['maxy'] - bbox['miny']) / tile_span['y'] - epsilon))
 
-
         # Does required bbox intersects bbox of data available on server?
         self.intersects = False
         for col in ['min_col', 'max_col']:
             for row in ['min_row', 'max_row']:
-                if (self.t_num_bbox['min_row'] <= self.t_num_bbox[row] and self.t_num_bbox[row] <= mat_num_bbox['max_row']) and \
-                   (self.t_num_bbox['min_col'] <= self.t_num_bbox[col] and self.t_num_bbox[col] <= mat_num_bbox['max_col']):
+                if (self.t_num_bbox['min_row'] <= self.t_num_bbox[row] and self.t_num_bbox[row] <= mat_num_bbox['max_row']) and (
+                        self.t_num_bbox['min_col'] <= self.t_num_bbox[col] and self.t_num_bbox[col] <= mat_num_bbox['max_col']):
                     self.intersects = True
-                    
+
         if not self.intersects:
             grass.warning(_('Region is out of server data extend.'))
             self.map_region = None
             return
 
-        # crop request bbox to server data bbox extend 
+        # crop request bbox to server data bbox extend
         if self.t_num_bbox['min_col'] < (mat_num_bbox['min_col']):
-            self.t_num_bbox['min_col']  = int(mat_num_bbox['min_col'])
+            self.t_num_bbox['min_col'] = int(mat_num_bbox['min_col'])
 
         if self.t_num_bbox['max_col'] > (mat_num_bbox['max_col']):
-            self.t_num_bbox['max_col']  = int(mat_num_bbox['max_col'])
+            self.t_num_bbox['max_col'] = int(mat_num_bbox['max_col'])
 
         if self.t_num_bbox['min_row'] < (mat_num_bbox['min_row']):
-            self.t_num_bbox['min_row'] = int(mat_num_bbox['min_row']) 
+            self.t_num_bbox['min_row'] = int(mat_num_bbox['min_row'])
 
         if self.t_num_bbox['max_row'] > (mat_num_bbox['max_row']):
-            self.t_num_bbox['max_row'] = int(mat_num_bbox['max_row']) 
+            self.t_num_bbox['max_row'] = int(mat_num_bbox['max_row'])
 
+        grass.debug(
+            't_num_bbox: min_col:%d max_col:%d min_row:%d max_row:%d' %
+            (self.t_num_bbox['min_col'],
+             self.t_num_bbox['max_col'],
+             self.t_num_bbox['min_row'],
+             self.t_num_bbox['max_row']),
+            3)
 
-        grass.debug('t_num_bbox: min_col:%d max_col:%d min_row:%d max_row:%d' % (self.t_num_bbox['min_col'], self.t_num_bbox['max_col'], self.t_num_bbox['min_row'], self.t_num_bbox['max_row']), 3)
+        num_tiles = (self.t_num_bbox['max_col'] - self.t_num_bbox['min_col'] + 1) * (
+            self.t_num_bbox['max_row'] - self.t_num_bbox['min_row'] + 1)
+        grass.message(
+            _('Fetching %d tiles with %d x %d pixel size per tile...') %
+            (num_tiles, tile_size['x'], tile_size['y']))
 
-        num_tiles = (self.t_num_bbox['max_col'] - self.t_num_bbox['min_col'] + 1) * (self.t_num_bbox['max_row'] - self.t_num_bbox['min_row'] + 1) 
-        grass.message(_('Fetching %d tiles with %d x %d pixel size per tile...') % (num_tiles, tile_size['x'], tile_size['y']))
-
         # georeference of raster, where tiles will be merged
         self.map_region = {}
         self.map_region['minx'] = self.t_num_bbox['min_col'] * tile_span['x'] + tl_corner['minx']
         self.map_region['maxy'] = tl_corner['maxy'] - (self.t_num_bbox['min_row']) * tile_span['y']
 
-        self.map_region['maxx'] = (self.t_num_bbox['max_col'] + 1) * tile_span['x'] + tl_corner['minx']
-        self.map_region['miny'] = tl_corner['maxy'] - (self.t_num_bbox['max_row'] + 1) * tile_span['y']
+        self.map_region['maxx'] = (
+            self.t_num_bbox['max_col'] + 1) * tile_span['x'] + tl_corner['minx']
+        self.map_region['miny'] = tl_corner[
+            'maxy'] - (self.t_num_bbox['max_row'] + 1) * tile_span['y']
 
         # size of raster, where tiles will be merged
-        self.map_region['cols'] = int(tile_size['x'] * (self.t_num_bbox['max_col'] -  self.t_num_bbox['min_col'] + 1))
-        self.map_region['rows'] = int(tile_size['y'] * (self.t_num_bbox['max_row'] -  self.t_num_bbox['min_row'] + 1))
+        self.map_region['cols'] = int(tile_size['x'] *
+                                      (self.t_num_bbox['max_col'] - self.t_num_bbox['min_col'] + 1))
+        self.map_region['rows'] = int(tile_size['y'] *
+                                      (self.t_num_bbox['max_row'] - self.t_num_bbox['min_row'] + 1))
 
-        # hold information about current column and row during iteration 
+        # hold information about current column and row during iteration
         self.i_col = self.t_num_bbox['min_col']
-        self.i_row = self.t_num_bbox['min_row'] 
+        self.i_row = self.t_num_bbox['min_row']
 
         # bbox for first tile request
-        self.query_bbox = { 
-                            'minx' : tl_corner['minx'],
-                            'maxy' : tl_corner['maxy'],
-                            'maxx' : tl_corner['minx'] + tile_span['x'],
-                            'miny' : tl_corner['maxy'] - tile_span['y'],
-                          }
+        self.query_bbox = {
+            'minx': tl_corner['minx'],
+            'maxy': tl_corner['maxy'],
+            'maxx': tl_corner['minx'] + tile_span['x'],
+            'miny': tl_corner['maxy'] - tile_span['y'],
+        }
 
         self.tile_ref = {
-                          'sizeX' : tile_size['x'],
-                          'sizeY' : tile_size['y']
-                        }
+            'sizeX': tile_size['x'],
+            'sizeY': tile_size['y']
+        }
 
     def _isGeoProj(self, proj):
-        """!Is it geographic projection? 
-        """       
-        if (proj.find("+proj=latlong")  != -1 or \
-            proj.find("+proj=longlat")  != -1):
+        """!Is it geographic projection?
+        """
+        if (proj.find("+proj=latlong") != -1 or
+                proj.find("+proj=longlat") != -1):
 
             return True
         return False
 
+
 class WMSRequestMgr(BaseRequestMgr):
-    def __init__(self, params, bbox, region, tile_size, proj_srs, cap_file = None):
+
+    def __init__(self, params, bbox, region, tile_size, proj_srs, cap_file=None):
         """!Initialize data needed for iteration through tiles.
         """
         self.version = params['wms_version']
         self.srs_param = params['srs']
 
-        proj = params['proj_name'] + "=" +  GetSRSParamVal(params['srs'])
-        self.url = params['url'] + ("SERVICE=WMS&REQUEST=GetMap&VERSION=%s&LAYERS=%s&WIDTH=%s&HEIGHT=%s&STYLES=%s&TRANSPARENT=%s" % \
-                  (params['wms_version'], params['layers'], tile_size['cols'], tile_size['rows'], params['styles'], \
-                   params['transparent']))
+        proj = params['proj_name'] + "=" + GetSRSParamVal(params['srs'])
+        self.url = params['url'] + ("SERVICE=WMS&REQUEST=GetMap&VERSION=%s&LAYERS=%s&WIDTH=%s&HEIGHT=%s&STYLES=%s&TRANSPARENT=%s" % (
+            params['wms_version'], params['layers'], tile_size['cols'], tile_size['rows'], params['styles'], params['transparent']))
 
         if params['bgcolor']:
-            self.url +=  "&BGCOLOR=" + params['bgcolor']
+            self.url += "&BGCOLOR=" + params['bgcolor']
 
-        self.url += "&" +proj+ "&" + "FORMAT=" + params['format']
+        self.url += "&" + proj + "&" + "FORMAT=" + params['format']
 
         self.bbox = bbox
         self.proj_srs = proj_srs
@@ -364,33 +416,35 @@
 
         if params['urlparams'] != "":
             self.url += "&" + params['urlparams']
-        
+
         cols = int(region['cols'])
         rows = int(region['rows'])
-        
-        # computes parameters of tiles 
-        self.num_tiles_x = cols / self.tile_cols 
+
+        # computes parameters of tiles
+        self.num_tiles_x = cols / self.tile_cols
         self.last_tile_x_size = cols % self.tile_cols
-        self.tile_length_x =  float(self.tile_cols) / float(cols) * (self.bbox['maxx'] - self.bbox['minx']) 
-        
+        self.tile_length_x = float(
+            self.tile_cols) / float(cols) * (self.bbox['maxx'] - self.bbox['minx'])
+
         self.last_tile_x = False
         if self.last_tile_x_size != 0:
             self.last_tile_x = True
             self.num_tiles_x = self.num_tiles_x + 1
-        
-        self.num_tiles_y = rows / self.tile_rows 
+
+        self.num_tiles_y = rows / self.tile_rows
         self.last_tile_y_size = rows % self.tile_rows
-        self.tile_length_y =  float(self.tile_rows) / float(rows) * (self.bbox['maxy'] - self.bbox['miny']) 
-        
+        self.tile_length_y = float(
+            self.tile_rows) / float(rows) * (self.bbox['maxy'] - self.bbox['miny'])
+
         self.last_tile_y = False
         if self.last_tile_y_size != 0:
             self.last_tile_y = True
             self.num_tiles_y = self.num_tiles_y + 1
-        
+
         self.tile_bbox = dict(self.bbox)
-        self.tile_bbox['maxx'] = self.bbox['minx']  + self.tile_length_x
+        self.tile_bbox['maxx'] = self.bbox['minx'] + self.tile_length_x
 
-        self.i_x = 0 
+        self.i_x = 0
         self.i_y = 0
 
         self.map_region = self.bbox
@@ -410,14 +464,14 @@
 
         if self.i_x >= self.num_tiles_x:
             return None
-            
+
         tile_ref['sizeX'] = self.tile_cols
         if self.i_x == self.num_tiles_x - 1 and self.last_tile_x:
             tile_ref['sizeX'] = self.last_tile_x_size
-         
+
         # set bbox for tile (N, S)
         if self.i_y != 0:
-            self.tile_bbox['miny'] -= self.tile_length_y 
+            self.tile_bbox['miny'] -= self.tile_length_y
             self.tile_bbox['maxy'] -= self.tile_length_y
         else:
             self.tile_bbox['maxy'] = self.bbox['maxy']
@@ -425,10 +479,14 @@
 
         tile_ref['sizeY'] = self.tile_rows
         if self.i_y == self.num_tiles_y - 1 and self.last_tile_y:
-            tile_ref['sizeY'] = self.last_tile_y_size 
+            tile_ref['sizeY'] = self.last_tile_y_size
 
         query_bbox = self._getQueryBbox(self.tile_bbox, self.proj_srs, self.srs_param, self.version)
-        query_url = self.url + "&" + "BBOX=%s,%s,%s,%s" % ( query_bbox['minx'],  query_bbox['miny'],  query_bbox['maxx'],  query_bbox['maxy'])
+        query_url = self.url + "&" + "BBOX=%s,%s,%s,%s" % (
+            query_bbox['minx'],
+            query_bbox['miny'],
+            query_bbox['maxx'],
+            query_bbox['maxy'])
 
         tile_ref['t_cols_offset'] = int(self.tile_cols * self.i_x)
         tile_ref['t_rows_offset'] = int(self.tile_rows * self.i_y)
@@ -436,18 +494,18 @@
         if self.i_y >= self.num_tiles_y - 1:
             self.i_y = 0
             self.i_x += 1
-            # set bbox for next tile (E, W)      
-            self.tile_bbox['maxx'] += self.tile_length_x 
-            self.tile_bbox['minx'] += self.tile_length_x 
+            # set bbox for next tile (E, W)
+            self.tile_bbox['maxx'] += self.tile_length_x
+            self.tile_bbox['minx'] += self.tile_length_x
         else:
             self.i_y += 1
 
         return query_url, tile_ref
 
     def _getQueryBbox(self, bbox, proj, srs_param, version):
-        """!Creates query bbox (used in request URL) 
+        """!Creates query bbox (used in request URL)
 
-        Mostly bbox is not modified but if WMS standard is 1.3.0 and 
+        Mostly bbox is not modified but if WMS standard is 1.3.0 and
         projection is geographic, the bbox x and y are in most cases flipped.
         """
         # CRS:84 and CRS:83 are exception (CRS:83 and CRS:27 need to be tested)
@@ -459,14 +517,14 @@
         return bbox
 
     def _flipBbox(self, bbox):
-        """ 
+        """
         Flips bbox values between this keys:
         maxy -> maxx
         maxx -> maxy
         miny -> minx
         minx -> miny
         @return copy of bbox with flipped coordinates
-        """  
+        """
 
         temp_bbox = dict(bbox)
         new_bbox = {}
@@ -477,8 +535,10 @@
 
         return new_bbox
 
+
 class WMTSRequestMgr(BaseRequestMgr):
-    def __init__(self, params, bbox, region, proj_srs, cap_file = None):
+
+    def __init__(self, params, bbox, region, proj_srs, cap_file=None):
         """!Initializes data needed for iteration through tiles.
         """
 
@@ -500,15 +560,17 @@
         root = cap_tree.getroot()
 
         # get layer tile matrix sets with required projection
-        mat_sets = self._getMatSets(root, params['layers'], params['srs'])  #[[TileMatrixSet, TileMatrixSetLink], ....]
+        # [[TileMatrixSet, TileMatrixSetLink], ....]
+        mat_sets = self._getMatSets(root, params['layers'], params['srs'])
 
         # TODO: what if more tile matrix sets have required srs (returned more than 1)?
         mat_set = mat_sets[0][0]
         mat_set_link = mat_sets[0][1]
         params['tile_matrix_set'] = mat_set.find(self.xml_ns.NsOws('Identifier')).text
 
-        # find tile matrix with resolution closest and smaller to wanted resolution 
-        tile_mat  = self._findTileMats(mat_set.findall(self.xml_ns.NsWmts('TileMatrix')), region, bbox)
+        # find tile matrix with resolution closest and smaller to wanted resolution
+        tile_mat = self._findTileMats(mat_set.findall(
+            self.xml_ns.NsWmts('TileMatrix')), region, bbox)
 
         # get extend of data available on server expressed in max/min rows and cols of tile matrix
         mat_num_bbox = self._getMatSize(tile_mat, mat_set_link)
@@ -532,8 +594,8 @@
         for layer in layers:
             layer_id = layer.find(self.xml_ns.NsOws('Identifier')).text
             if layer_id == layer_name:
-                ch_layer = layer 
-                break  
+                ch_layer = layer
+                break
 
         if ch_layer is None:
             grass.fatal(_("Layer '%s' was not found in capabilities file") % layer_name)
@@ -543,10 +605,10 @@
         suitable_mat_sets = []
         tileMatrixSets = contents.findall(self.xml_ns.NsWmts('TileMatrixSet'))
 
-        for link in  mat_set_links:
+        for link in mat_set_links:
             mat_set_link_id = link.find(self.xml_ns.NsWmts('TileMatrixSet')).text
             for mat_set in tileMatrixSets:
-                mat_set_id = mat_set.find(self.xml_ns.NsOws('Identifier')).text 
+                mat_set_id = mat_set.find(self.xml_ns.NsOws('Identifier')).text
                 if mat_set_id != mat_set_link_id:
                     continue
                 mat_set_srs = self._getMatSetSrs(mat_set)
@@ -554,9 +616,11 @@
                     suitable_mat_sets.append([mat_set, link])
 
         if not suitable_mat_sets:
-            grass.fatal(_("Layer '%s' is not available with %s code.") % (layer_name,  "EPSG:" + str(srs)))
+            grass.fatal(
+                _("Layer '%s' is not available with %s code.") %
+                (layer_name, "EPSG:" + str(srs)))
 
-        return suitable_mat_sets # [[TileMatrixSet, TileMatrixSetLink], ....]
+        return suitable_mat_sets  # [[TileMatrixSet, TileMatrixSetLink], ....]
 
     def _getMatSetSrs(self, mat_set):
 
@@ -564,11 +628,13 @@
 
     def _findTileMats(self, tile_mats, region, bbox):
         """!Find best tile matrix set for requested resolution.
-        """        
+        """
         scale_dens = []
 
-        scale_dens.append((bbox['maxy'] - bbox['miny']) / region['rows'] * self._getMetersPerUnit()  / self.pixel_size)
-        scale_dens.append((bbox['maxx'] - bbox['minx']) / region['cols'] * self._getMetersPerUnit() / self.pixel_size)
+        scale_dens.append((bbox['maxy'] - bbox['miny']) / region['rows']
+                          * self._getMetersPerUnit() / self.pixel_size)
+        scale_dens.append((bbox['maxx'] - bbox['minx']) / region['cols']
+                          * self._getMetersPerUnit() / self.pixel_size)
 
         scale_den = min(scale_dens)
 
@@ -580,11 +646,11 @@
                 best_t_mat = t_mat
                 first = False
                 continue
-                
+
             best_diff = best_scale_den - scale_den
             mat_diff = mat_scale_den - scale_den
             if (best_diff < mat_diff  and  mat_diff < 0) or \
-               (best_diff > mat_diff  and  best_diff > 0):
+               (best_diff > mat_diff and best_diff > 0):
                 best_t_mat = t_mat
                 best_scale_den = mat_scale_den
 
@@ -592,7 +658,7 @@
 
     def _getMetersPerUnit(self):
         """!Get coefficient which allows converting units of request projection into meters.
-        """  
+        """
         if self.meters_per_unit:
             return self.meters_per_unit
 
@@ -605,16 +671,16 @@
                     break
             equator_perim = 2 * pi * a
             # meters per degree on equator
-            self.meters_per_unit = equator_perim / 360 
+            self.meters_per_unit = equator_perim / 360
 
         # other units
         elif '+to_meter' in self.proj_srs:
             proj_params = self.proj_srs.split(' ')
             for param in proj_params:
                 if '+to_meter' in param:
-                    self.meters_per_unit = 1/float(param.split('=')[1])
+                    self.meters_per_unit = 1 / float(param.split('=')[1])
                     break
-        # coordinate system in meters        
+        # coordinate system in meters
         else:
             self.meters_per_unit = 1
 
@@ -643,7 +709,7 @@
             limit_id = limit_tile_mat.text
 
             if limit_id == tile_mat_id:
-                for i in [['min_row', 'MinTileRow'], ['max_row', 'MaxTileRow'], \
+                for i in [['min_row', 'MinTileRow'], ['max_row', 'MaxTileRow'],
                           ['min_col', 'MinTileCol'], ['max_col', 'MaxTileCol']]:
                     i_tag = limit.find(self.xml_ns.NsWmts(i[1]))
 
@@ -657,7 +723,7 @@
 
     def _computeRequestData(self, tile_mat, params, bbox, mat_num_bbox, mat_set_srs):
         """!Initialize data needed for iteration through tiles.
-        """  
+        """
         scale_den = float(tile_mat.find(self.xml_ns.NsWmts('ScaleDenominator')).text)
 
         pixel_span = scale_den * self.pixel_size / self._getMetersPerUnit()
@@ -668,9 +734,10 @@
         tl_corner['minx'] = float(tl_str[0])
         tl_corner['maxy'] = float(tl_str[1])
 
-        #TODO do it more generally WMS cap parser may use it in future(not needed now)???
-        s = Srs(mat_set_srs) #NOTE not used params['srs'], it is just number, encoding needed
-        # TODO needs to be tested, tried only on http://www.landesvermessung.sachsen.de/geoserver/gwc/service/wmts?:
+        # TODO do it more generally WMS cap parser may use it in future(not needed now)???
+        s = Srs(mat_set_srs)  # NOTE not used params['srs'], it is just number, encoding needed
+        # TODO needs to be tested, tried only on
+        # http://www.landesvermessung.sachsen.de/geoserver/gwc/service/wmts?:
         if s.getcode() == 'EPSG:4326' and s.encoding in ('uri', 'urn'):
             grass.warning('switch')
             (tl_corner['minx'], tl_corner['maxy']) = (tl_corner['maxy'], tl_corner['minx'])
@@ -682,37 +749,42 @@
 
         self.tile_size['x'] = int(tile_mat.find(self.xml_ns.NsWmts('TileWidth')).text)
         tile_span['x'] = pixel_span * self.tile_size['x']
-        
+
         self.tile_size['y'] = int(tile_mat.find(self.xml_ns.NsWmts('TileHeight')).text)
         tile_span['y'] = pixel_span * self.tile_size['y']
 
-        self.url = params['url'] + ("SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&" \
-                                    "LAYER=%s&STYLE=%s&FORMAT=%s&TILEMATRIXSET=%s&TILEMATRIX=%s" % \
-                                   (params['layers'], params['styles'], params['format'],
-                                    params['tile_matrix_set'], tile_mat.find(self.xml_ns.NsOws('Identifier')).text ))
+        self.url = params['url'] + ("SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&"
+                                    "LAYER=%s&STYLE=%s&FORMAT=%s&TILEMATRIXSET=%s&TILEMATRIX=%s" %
+                                    (params['layers'], params['styles'], params['format'],
+                                     params['tile_matrix_set'], tile_mat.find(self.xml_ns.NsOws('Identifier')).text))
 
-        BaseRequestMgr._computeRequestData(self, bbox, tl_corner, tile_span, self.tile_size, mat_num_bbox)
+        BaseRequestMgr._computeRequestData(
+            self, bbox, tl_corner, tile_span, self.tile_size, mat_num_bbox)
 
     def GetNextTile(self):
         """!Get url for tile request from server and information for merging the tile with other tiles.
         """
         if not self.intersects or self.i_col > self.t_num_bbox['max_col']:
-            return None 
-                
-        query_url = self.url + "&TILECOL=%i&TILEROW=%i" % (int(self.i_col), int(self.i_row)) 
+            return None
 
-        self.tile_ref['t_cols_offset'] = int(self.tile_size['x'] * (self.i_col - self.t_num_bbox['min_col']))
-        self.tile_ref['t_rows_offset'] = int(self.tile_size['y'] * (self.i_row - self.t_num_bbox['min_row']))
+        query_url = self.url + "&TILECOL=%i&TILEROW=%i" % (int(self.i_col), int(self.i_row))
 
+        self.tile_ref['t_cols_offset'] = int(
+            self.tile_size['x'] * (self.i_col - self.t_num_bbox['min_col']))
+        self.tile_ref['t_rows_offset'] = int(
+            self.tile_size['y'] * (self.i_row - self.t_num_bbox['min_row']))
+
         if self.i_row >= self.t_num_bbox['max_row']:
-            self.i_row =  self.t_num_bbox['min_row']
+            self.i_row = self.t_num_bbox['min_row']
             self.i_col += 1
         else:
-            self.i_row += 1 
+            self.i_row += 1
 
         return query_url, self.tile_ref
 
+
 class OnEarthRequestMgr(BaseRequestMgr):
+
     def __init__(self, params, bbox, region, proj_srs, tile_service):
         """!Initializes data needed for iteration through tiles.
         """
@@ -726,7 +798,8 @@
         root = self.cap_tree.getroot()
 
         # parse tile service file and get needed data for making tile requests
-        url, self.tile_span, t_patt_bbox, self.tile_size = self._parseTileService(root, bbox, region, params)
+        url, self.tile_span, t_patt_bbox, self.tile_size = self._parseTileService(
+            root, bbox, region, params)
         self.url = url
         self.url[0] = params['url'] + url[0]
         # initialize data needed for iteration through tiles
@@ -743,7 +816,9 @@
         tiled_patterns = root.find('TiledPatterns')
         tile_groups = self._getAllTiledGroup(tiled_patterns)
         if not tile_groups:
-            grass.fatal(_("Unable to parse tile service file. \n No tag '%s' was found.") % 'TiledGroup')
+            grass.fatal(
+                _("Unable to parse tile service file. \n No tag '%s' was found.") %
+                'TiledGroup')
 
         req_group = None
         for group in tile_groups:
@@ -771,7 +846,7 @@
         tile_span = {}
         tile_span['x'] = abs(t_bbox[0] - t_bbox[2])
         tile_span['y'] = abs(t_bbox[1] - t_bbox[3])
-                   
+
         tile_pattern_bbox = req_group.find('LatLonBoundingBox')
 
         t_patt_bbox = {}
@@ -784,7 +859,7 @@
 
         return url, tile_span, t_patt_bbox, tile_size
 
-    def _getAllTiledGroup(self, parent, tiled_groups = None):
+    def _getAllTiledGroup(self, parent, tiled_groups=None):
         """!Get all 'TileGroup' elements
         """
         if not tiled_groups:
@@ -812,7 +887,8 @@
         t_res = {}
         best_patt = None
         for pattern in group_t_patts:
-            url, t_bbox, width, height = self.cap_tree.gettilepatternurldata(pattern.text.split('\n')[0])
+            url, t_bbox, width, height = self.cap_tree.gettilepatternurldata(pattern.text.split(
+                '\n')[0])
 
             t_res['x'] = abs(t_bbox[0] - t_bbox[2]) / width
             t_res['y'] = abs(t_bbox[1] - t_bbox[3]) / height
@@ -822,12 +898,12 @@
                 best_patt = pattern
                 first = False
                 continue
-            
+
             best_diff = best_res - res[comp_res]
             tile_diff = t_res[comp_res] - res[comp_res]
 
             if (best_diff < tile_diff  and  tile_diff < 0) or \
-               (best_diff > tile_diff  and  best_diff > 0):
+               (best_diff > tile_diff and best_diff > 0):
 
                 best_res = t_res[comp_res]
                 best_patt = pattern
@@ -835,14 +911,14 @@
         return best_patt
 
     def _insTimeToTilePatternUrl(self, url_params, urls):
-        """!Time can be variable in some urls in OnEarth TMS. 
+        """!Time can be variable in some urls in OnEarth TMS.
             Insert requested time from 'urlparams' into the variable if any url of urls contains the variable.
         """
         url = None
         not_sup_params = []
         url_params_list = url_params.split('&')
 
-        for param in  url_params_list:
+        for param in url_params_list:
             try:
                 k, v = param.split('=')
             except ValueError:
@@ -854,63 +930,75 @@
                 continue
 
             has_time_var = False
-            for url in urls: 
+            for url in urls:
                 url_p_idxs = self.geturlparamidxs(url, k)
                 if not url_p_idxs:
                     continue
 
-                url_p_value = url[url_p_idxs[0] + len(k + '=') : url_p_idxs[1]]
+                url_p_value = url[url_p_idxs[0] + len(k + '='): url_p_idxs[1]]
 
                 if url_p_value[:2] == '${'  and \
                    url_p_value[len(url_p_value) - 1] == '}':
-                   url = url[:url_p_idxs[0]] + param + url[url_p_idxs[1]:]   
-                   has_time_var = True
-                   break
+                    url = url[:url_p_idxs[0]] + param + url[url_p_idxs[1]:]
+                    has_time_var = True
+                    break
 
             if not has_time_var:
-                grass.warning(_("Parameter '%s' in '%s' is not variable in tile pattern url.") % (k, 'urlparams'))
+                grass.warning(
+                    _("Parameter '%s' in '%s' is not variable in tile pattern url.") %
+                    (k, 'urlparams'))
 
         if not_sup_params:
-                grass.warning(_("%s driver supports only '%s' parameter in '%s'. Other parameters are ignored.") % \
-                               ('OnEarth GRASS', 'time', 'urlparams'))
+            grass.warning(
+                _("%s driver supports only '%s' parameter in '%s'. Other parameters are ignored.") %
+                ('OnEarth GRASS', 'time', 'urlparams'))
 
         return url
 
     def _computeRequestData(self, bbox, t_patt_bbox, tile_span, tile_size):
         """!Initialize data needed for iteration through tiles.
-        """  
+        """
         epsilon = 1e-15
         mat_num_bbox = {}
 
         mat_num_bbox['min_row'] = mat_num_bbox['min_col'] = 0
-        mat_num_bbox['max_row'] = floor((t_patt_bbox['maxy'] - t_patt_bbox['miny'])/ tile_span['y'] + epsilon)  
-        mat_num_bbox['max_col'] = floor((t_patt_bbox['maxx'] - t_patt_bbox['minx'])/ tile_span['x'] + epsilon)  
+        mat_num_bbox['max_row'] = floor(
+            (t_patt_bbox['maxy'] - t_patt_bbox['miny']) / tile_span['y'] + epsilon)
+        mat_num_bbox['max_col'] = floor(
+            (t_patt_bbox['maxx'] - t_patt_bbox['minx']) / tile_span['x'] + epsilon)
 
-        BaseRequestMgr._computeRequestData(self, bbox, t_patt_bbox, self.tile_span, self.tile_size, mat_num_bbox)
+        BaseRequestMgr._computeRequestData(
+            self,
+            bbox,
+            t_patt_bbox,
+            self.tile_span,
+            self.tile_size,
+            mat_num_bbox)
 
-
     def GetNextTile(self):
         """!Get url for tile request from server and information for merging the tile with other tiles
         """
         if self.i_col > self.t_num_bbox['max_col']:
-            return None 
+            return None
 
         x_offset = self.tile_span['x'] * self.i_col
         y_offset = self.tile_span['y'] * self.i_row
 
-        query_url = self.url[0] + "&" + "bbox=%s,%s,%s,%s" % (float(self.query_bbox['minx'] + x_offset),  
-                                                              float(self.query_bbox['miny'] - y_offset),  
-                                                              float(self.query_bbox['maxx'] + x_offset),  
-                                                              float(self.query_bbox['maxy'] - y_offset)) + self.url[1]
+        query_url = self.url[0] + "&" + "bbox=%s,%s,%s,%s" % (
+            float(self.query_bbox['minx'] + x_offset),
+            float(self.query_bbox['miny'] - y_offset),
+            float(self.query_bbox['maxx'] + x_offset),
+            float(self.query_bbox['maxy'] - y_offset)) + self.url[1]
 
-        self.tile_ref['t_cols_offset'] = int(self.tile_size['y'] * (self.i_col - self.t_num_bbox['min_col']))
-        self.tile_ref['t_rows_offset'] = int(self.tile_size['x'] * (self.i_row - self.t_num_bbox['min_row']))
+        self.tile_ref['t_cols_offset'] = int(
+            self.tile_size['y'] * (self.i_col - self.t_num_bbox['min_col']))
+        self.tile_ref['t_rows_offset'] = int(
+            self.tile_size['x'] * (self.i_row - self.t_num_bbox['min_row']))
 
         if self.i_row >= self.t_num_bbox['max_row']:
-            self.i_row =  self.t_num_bbox['min_row']
+            self.i_row = self.t_num_bbox['min_row']
             self.i_col += 1
         else:
-            self.i_row += 1 
+            self.i_row += 1
 
         return query_url, self.tile_ref
-

Modified: grass/trunk/scripts/r.in.wms/wms_gdal_drv.py
===================================================================
--- grass/trunk/scripts/r.in.wms/wms_gdal_drv.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/r.in.wms/wms_gdal_drv.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -1,5 +1,5 @@
 """!
- at brief GDAL WMS driver. 
+ at brief GDAL WMS driver.
 
 List of classes:
  - wms_drv::NullDevice
@@ -14,7 +14,7 @@
 """
 
 import os
-import grass.script as grass 
+import grass.script as grass
 
 try:
     from osgeo import gdal
@@ -26,129 +26,133 @@
 
 from wms_base import WMSBase, GetSRSParamVal
 
+
 class NullDevice():
+
     def write(self, s):
         pass
 
+
 class WMSGdalDrv(WMSBase):
+
     def _createXML(self):
         """!Create XML for GDAL WMS driver
-        
+
         @return path to XML file
         """
         self._debug("_createXML", "started")
-        
+
         gdal_wms = etree.Element("GDAL_WMS")
         service = etree.SubElement(gdal_wms, "Service")
         name = etree.Element("name")
-        service.set("name","WMS")
-        
+        service.set("name", "WMS")
+
         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.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'])
-        
+
         image_format = etree.SubElement(service, "ImageFormat")
         image_format.text = self.params['format']
-        
+
         image_format = etree.SubElement(service, "Transparent")
         image_format.text = self.params['transparent']
-        
+
         layers = etree.SubElement(service, "Layers")
         layers.text = self.params['layers']
-        
+
         styles = etree.SubElement(service, "Styles")
         styles.text = self.params['styles']
-        
+
         data_window = etree.SubElement(gdal_wms, "DataWindow")
 
         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.text = str(self.bbox['maxy']) 
-        
+        upper_left_y.text = str(self.bbox['maxy'])
+
         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.text = str(self.bbox['miny'])
-        
+
         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.text = str(self.region['rows']) 
-        
+        size_y.text = str(self.region['rows'])
+
         # RGB + alpha
         self.temp_map_bands_num = 4
         block_size_x = etree.SubElement(gdal_wms, "BandsCount")
         block_size_x.text = str(self.temp_map_bands_num)
-        
+
         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.text = str(self.tile_size['rows'])
-        
+
         xml_file = self._tempfile()
-        
+
         etree.ElementTree(gdal_wms).write(xml_file)
-        
+
         self._debug("_createXML", "finished -> %s" % xml_file)
-        
+
         return xml_file
-    
+
     def _download(self):
         """!Downloads data from WMS server using GDAL WMS driver
-        
+
         @return temp_map with stored downloaded data
         """
         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.
-        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 " +
                             "geographic projection, \n try 'WMS_GRASS' driver or use WMS version 1.1.1."))
 
         self._debug("_download", "started")
-        
-        temp_map = self._tempfile()        
 
+        temp_map = self._tempfile()
+
         xml_file = self._createXML()
         wms_dataset = gdal.Open(xml_file, gdal.GA_ReadOnly)
         grass.try_remove(xml_file)
         if wms_dataset is None:
             grass.fatal(_("Unable to open GDAL WMS driver"))
-        
+
         self._debug("_download", "GDAL dataset created")
-        
+
         driver = gdal.GetDriverByName(self.gdal_drv_format)
         if driver is None:
             grass.fatal(_("Unable to find %s driver" % format))
-        
+
         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':
             grass.fatal(_('Driver %s supports CreateCopy() method.') % self.gdal_drv_name)
-        
+
         self._debug("_download", "calling GDAL CreateCopy...")
-        
+
         temp_map_dataset = driver.CreateCopy(temp_map, wms_dataset, 0)
-        
+
         if temp_map_dataset is None:
             grass.fatal(_("Incorrect WMS query"))
-        
-        temp_map_dataset  = None
+
+        temp_map_dataset = None
         wms_dataset = None
-        
+
         self._debug("_download", "finished")
-        
+
         return temp_map

Modified: grass/trunk/scripts/r.mask/r.mask.py
===================================================================
--- grass/trunk/scripts/r.mask/r.mask.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/r.mask/r.mask.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -75,12 +75,13 @@
 
 def cleanup():
     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:
-        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():
     raster = options['raster']
     maskcats = options['maskcats']
@@ -95,13 +96,13 @@
         grass.fatal(_("Either parameter <raster> ot parameter <vector> is required"))
 
     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:
         # -> remove
         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"))
         else:
             grass.fatal(_("No existing MASK to remove"))
@@ -112,9 +113,9 @@
                 grass.fatal(_("MASK already found in current mapset. Delete first or overwrite."))
             else:
                 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:
             # check if input raster exists
             if not grass.find_file(raster)['file']:
@@ -125,7 +126,12 @@
                     grass.fatal(_("The raster map <%s> must be integer (CELL type) "
                                   " 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.close()
             p.wait()
@@ -133,13 +139,13 @@
             vector_name = grass.find_file(vector, 'vector')['fullname']
             if not vector_name:
                 grass.fatal(_("Vector map <%s> not found") % vector)
-            
+
             # parser bug?
             if len(cats) == 0:
                 cats = None
             if len(where) == 0:
                 where = None
-            
+
             if grass.vector_info_topo(vector_name)['areas'] < 1:
                 grass.warning(_("No area found in vector map <%s>. "
                                 "Creating a convex hull for MASK.") % vector_name)
@@ -152,23 +158,25 @@
                                       input=vector_name, output=tmp_hull,
                                       layer=layer, cats=cats, where=where)
                 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:
                 to_rast_input = vector_name
-            
+
             env = os.environ.copy()
             if grass.verbosity() > 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:
             global tmp
             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.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"))
         else:
             grass.verbose(_("Raster MASK created"))

Modified: grass/trunk/scripts/r.out.xyz/r.out.xyz.py
===================================================================
--- grass/trunk/scripts/r.out.xyz/r.out.xyz.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/r.out.xyz/r.out.xyz.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -37,6 +37,7 @@
 from grass.script import core as grass
 from grass.exceptions import CalledModuleError
 
+
 def main():
     # if no output filename, output to stdout
     output = options['output']

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

Modified: grass/trunk/scripts/r.plane/r.plane.py
===================================================================
--- grass/trunk/scripts/r.plane/r.plane.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/r.plane/r.plane.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -59,38 +59,37 @@
 #%end
 #%option
 #% key: type
-#% type: string 
+#% type: string
 #% options: CELL,FCELL,DCELL
 #% description: Type of raster map to be created
 #% answer: FCELL
 #%end
 
-import sys
-import os
 import math
 import string
-import grass.script as grass
+import grass.script as gscript
 
+
 def main():
     name = options['output']
     type = options['type']
     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 ###
     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:
-	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)
     cosaz = math.cos(az_r)
 
@@ -102,27 +101,28 @@
     kz = el - ea * sinaz * tandip - no * cosaz * tandip
 
     if type == "CELL":
-	round = "round"
-	dtype = "int"
+        round = "round"
+        dtype = "int"
     elif type == "FCELL":
-	round = ""
-	dtype = "float"
+        round = ""
+        dtype = "float"
     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__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     main()

Modified: grass/trunk/scripts/r.reclass.area/r.reclass.area.py
===================================================================
--- grass/trunk/scripts/r.reclass.area/r.reclass.area.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/r.reclass.area/r.reclass.area.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -204,7 +204,7 @@
     limit = float(value)
     if mode == 'greater' and method == 'rmarea':
         grass.fatal(_("You have to specify mode='lesser' with method='rmarea'"))
-    
+
     if not grass.find_file(infile)['name']:
         grass.fatal(_("Raster map <%s> not found") % infile)
 

Modified: grass/trunk/scripts/r.shade/r.shade.py
===================================================================
--- grass/trunk/scripts/r.shade/r.shade.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/r.shade/r.shade.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -111,15 +111,17 @@
             relief_map = relief_map_tmp
             to_remove.append(relief_map_tmp)
         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])
         gcore.run_command('r.composite', red=tmp_r, green=tmp_g,
                           blue=tmp_b, output=output_map)
         remove(to_remove)  # who knows if finally is called when exit
-    except CalledModuleError, error:
+    except CalledModuleError as error:
         remove(to_remove)
         # 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__":

Modified: grass/trunk/scripts/r.tileset/r.tileset.py
===================================================================
--- grass/trunk/scripts/r.tileset/r.tileset.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/r.tileset/r.tileset.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -106,13 +106,14 @@
 # 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 projection - [0] is proj.4 text, [1] is scale
+from __future__ import print_function
 
 import sys
 import tempfile
 import math
 
 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
 
 
@@ -158,7 +159,7 @@
     errors = 0
     points = []
     try:
-        ret = grass.read_command('m.proj',
+        ret = gcore.read_command('m.proj',
                                  quiet=True,
                                  flags='d',
                                  proj_in=source['proj'],
@@ -166,10 +167,10 @@
                                  sep=';',
                                  input=file)
     except CalledModuleError:
-        grass.fatal(cs2cs + ' failed')
+        gcore.fatal(cs2cs + ' failed')
 
     if not ret:
-        grass.fatal(cs2cs + ' failed')
+        gcore.fatal(cs2cs + ' failed')
 
     for line in ret.splitlines():
         if "*" in line:
@@ -238,40 +239,42 @@
     max_rows = int(options['maxrows']) - int(options['overlap'])
 
     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" %
                       (options['maxcols'], options['overlap'])))
     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" %
                       (options['maxrows'], options['overlap'])))
     # destination projection
     if not options['destproj']:
-        dest_proj = grass.read_command('g.proj',
+        dest_proj = gcore.read_command('g.proj',
                                        quiet=True,
                                        flags='jf').rstrip('\n')
         if not dest_proj:
-            grass.fatal(_('g.proj failed'))
+            gcore.fatal(_('g.proj failed'))
     else:
         dest_proj = options['destproj']
-    grass.debug("Getting destination projection -> '%s'" % dest_proj)
+    gcore.debug("Getting destination projection -> '%s'" % dest_proj)
 
     # projection scale
     if not options['destscale']:
-        ret = grass.parse_command('g.proj',
+        ret = gcore.parse_command('g.proj',
                                   quiet=True,
                                   flags='j')
         if not ret:
-            grass.fatal(_('g.proj failed'))
+            gcore.fatal(_('g.proj failed'))
 
         if '+to_meter' in ret:
             dest_scale = ret['+to_meter'].strip()
         else:
-            grass.warning(_("Scale (%s) not found, assuming '1'") % '+to_meter')
+            gcore.warning(
+                _("Scale (%s) not found, assuming '1'") %
+                '+to_meter')
             dest_scale = '1'
     else:
         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
     srs_source = {'proj': options['sourceproj'],
@@ -279,17 +282,17 @@
     srs_dest = {'proj': dest_proj, 'scale': float(dest_scale)}
 
     if options['region']:
-        grass.run_command('g.region',
+        gcore.run_command('g.region',
                           quiet=True,
                           region=options['region'])
-    dest_bbox = grass.region()
-    grass.debug('Getting destination region')
+    dest_bbox = gcore.region()
+    gcore.debug('Getting destination region')
 
     # output field separator
     fs = separator(options['separator'])
 
     # 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_source_points, errors_dest = projectPoints(dest_bbox_points,
@@ -297,24 +300,24 @@
                                                          dest=srs_source)
 
     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 of the current location"))
 
     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_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']
     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,
                                            x_metric, y_metric)
@@ -324,12 +327,14 @@
     # 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_
     # 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 small regions far from the critical areas of projections this makes very little difference
     # 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.append(max(source_bbox_dest_lengths['x']))
@@ -342,7 +347,7 @@
     # I'm going to make the numbers all simpler and add this extra cell to
     # every tile.
 
-    grass.message(_('Computing tiling...'))
+    gcore.message(_('Computing tiling...'))
     tiles = [-1, -1]
     tile_base_size = [-1, -1]
     tiles_extra_1 = [-1, -1]
@@ -363,7 +368,7 @@
         # Add overlap to tiles (doesn't effect tileset_size
         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]))
 
     ximax = tiles[0]
@@ -380,16 +385,21 @@
     tile_bbox = {'w': -1, 's': -1, 'e': -1, 'n': -1}
 
     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))
 
     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
         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_dest_bbox_points, errors = projectPoints(tile_bbox_points,
                                                           source=srs_source,
@@ -397,24 +407,24 @@
             tile_dest_bbox = pointsToBbox(tile_dest_bbox_points)
             if bboxesIntersect(tile_dest_bbox, dest_bbox):
                 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['n'], tile_size_overlap[0],
-                           tile_size_overlap[1])
+                           tile_size_overlap[1]))
                 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['n'], tile_size_overlap[0],
-                           tile_size_overlap[1])
+                           tile_size_overlap[1]))
                 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['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
         xi += 1
 
 if __name__ == "__main__":
     cs2cs = 'cs2cs'
-    options, flags = grass.parser()
+    options, flags = gcore.parser()
     sys.exit(main())

Modified: grass/trunk/scripts/r.unpack/r.unpack.py
===================================================================
--- grass/trunk/scripts/r.unpack/r.unpack.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/r.unpack/r.unpack.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -82,7 +82,8 @@
         if os.environ.get('GRASS_OVERWRITE', '0') != '1':
             grass.fatal(_('Raster map <{name}> already exists'.format(name=map_name)))
         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
     tar.extractall()
@@ -100,36 +101,37 @@
 
     if flags['o']:
         grass.warning(_("Overriding projection check (using current location's projection)."))
-        
+
     else:
-        
+
         diff_result_1 = diff_result_2 = None
-        
+
         proj_info_file_1 = 'PROJ_INFO'
         proj_info_file_2 = os.path.join(mset_dir, '..', 'PERMANENT', 'PROJ_INFO')
 
         skip_projection_check = False
         if not os.path.exists(proj_info_file_1):
             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
 
         if not skip_projection_check:
             if not grass.compare_key_value_text_files(filename_a=proj_info_file_1,
                                                       filename_b=proj_info_file_2,
-                                                      proj=True):                                                      
+                                                      proj=True):
                 diff_result_1 = diff_files(proj_info_file_1, proj_info_file_2)
-        
+
             proj_units_file_1 = '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,
                                                       filename_b=proj_units_file_2,
-                                                      units=True):                                                      
+                                                      units=True):
                 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:
                     grass.warning(_("Difference between PROJ_INFO file of packed map "
                                     "and of current location:\n{diff}").format(diff=''.join(diff_result_1)))

Modified: grass/trunk/scripts/r3.in.xyz/r3.in.xyz.py
===================================================================
--- grass/trunk/scripts/r3.in.xyz/r3.in.xyz.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/r3.in.xyz/r3.in.xyz.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -280,7 +280,7 @@
                                       **addl_opts)
 
         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:
             # wait for the ones launched so far to finish
@@ -299,7 +299,7 @@
 
     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=',',
                                 pattern='tmp.r3xyz.%d.*' % os.getpid()).rstrip(os.linesep)
     grass.debug(slices)

Modified: grass/trunk/scripts/v.build.all/v.build.all.py
===================================================================
--- grass/trunk/scripts/v.build.all/v.build.all.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.build.all/v.build.all.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -22,6 +22,7 @@
 from grass.script import core as grass
 from grass.exceptions import CalledModuleError
 
+
 def main():
     env = grass.gisenv()
     mapset = env['MAPSET']
@@ -29,17 +30,17 @@
 
     vectors = grass.list_grouped('vect')[mapset]
     num_vectors = len(vectors)
-    
+
     if grass.verbosity() < 2:
         quiet = True
     else:
         quiet = False
-        
+
     i = 1
     for vect in vectors:
         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)
         try:
             grass.run_command("v.build", map=map, quiet=quiet)

Modified: grass/trunk/scripts/v.centroids/v.centroids.py
===================================================================
--- grass/trunk/scripts/v.centroids/v.centroids.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.centroids/v.centroids.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -50,20 +50,19 @@
 #%end
 
 import sys
-import os
-import re
-import grass.script as grass
+import grass.script as gscript
 
+
 def main():
     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)
 
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     main()

Modified: grass/trunk/scripts/v.db.addcolumn/v.db.addcolumn.py
===================================================================
--- grass/trunk/scripts/v.db.addcolumn/v.db.addcolumn.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.db.addcolumn/v.db.addcolumn.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -3,7 +3,7 @@
 ############################################################################
 #
 # MODULE:       v.db.addcolumnumn
-# AUTHOR(S):    Moritz Lennert 
+# AUTHOR(S):    Moritz Lennert
 #               Converted to Python by Glynn Clements
 # PURPOSE:      interface to db.execute to add a column to the attribute table
 #               connected to a given vector map
@@ -42,29 +42,31 @@
 import os
 import grass.script as grass
 
+
 def main():
-    map     = options['map']
-    layer   = options['layer']
+    map = options['map']
+    layer = options['layer']
     columns = options['columns']
     columns = [col.strip() for col in columns.split(',')]
-    
+
     # does map exist in CURRENT 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:
         grass.fatal(_("Vector map <%s> not found in current mapset") % map)
-    
+
     try:
         f = grass.vector_db(map)[int(layer)]
     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']
-    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:
         if not col:
             grass.fatal(_("There is an empty column. Did you leave a trailing comma?"))
@@ -73,13 +75,13 @@
             grass.error(_("Column <%s> is already in the table. Skipping.") % col_name)
             continue
         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))
         grass.debug("ALTER TABLE %s ADD COLUMN %s" % (table, col))
         p.stdin.close()
         if p.wait() != 0:
             grass.fatal(_("Unable to add column <%s>.") % col)
-    
+
     # write cmd history:
     grass.vector_history(map)
 

Modified: grass/trunk/scripts/v.db.addtable/v.db.addtable.py
===================================================================
--- grass/trunk/scripts/v.db.addtable/v.db.addtable.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.db.addtable/v.db.addtable.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -3,7 +3,7 @@
 ############################################################################
 #
 # MODULE:       v.db.addtable
-# AUTHOR(S):    Markus Neteler 
+# AUTHOR(S):    Markus Neteler
 #               Converted to Python by Glynn Clements
 #               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
@@ -23,14 +23,14 @@
 #%end
 #%option G_OPT_V_MAP
 #%end
-#%option 
+#%option
 #% key: table
 #% type: string
 #% description: Name of new attribute table (default: vector map name)
 #% required: no
 #% guisection: Definition
 #%end
-#%option 
+#%option
 #% key: layer
 #% type: integer
 #% description: Layer number where to add new attribute table
@@ -64,14 +64,14 @@
     layer = options['layer']
     columns = options['columns']
     key = options['key']
-    
+
     # does map exist in CURRENT 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)
-    
+
     map_name = vector.split('@')[0]
-    
+
     if not table:
         if layer == '1':
             grass.verbose(_("Using vector map name as table name: <%s>") % map_name)
@@ -79,44 +79,46 @@
         else:
             # to avoid tables with identical names on higher layers
             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:
         grass.verbose(_("Using user specified table name: %s") % table)
-    
+
     # 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..."))
     kv = grass.db_connection()
     database = kv['database']
     driver = kv['driver']
     schema = kv['schema']
-    
+
     # maybe there is already a table linked to the selected layer?
     nuldev = file(os.devnull, 'w')
     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)
     except KeyError:
         pass
-    
+
     # 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 columns:
             column_def = [x.strip().lower() for x in columns.strip().split(',')]
         else:
             column_def = []
-        
+
         # if not existing, create it:
         column_def_key = "%s integer" % key
         if column_def_key not in column_def:
             column_def.insert(0, column_def_key)
         column_def = ','.join(column_def)
-        
+
         grass.verbose(_("Creating table with columns (%s)...") % column_def)
-        
+
         sql = "CREATE TABLE %s (%s)" % (table, column_def)
         try:
             grass.run_command('db.execute',
@@ -127,22 +129,22 @@
     # connect the map to the DB:
     if schema:
         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:
     # (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:"))
     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:
     grass.vector_history(map_name)
-    
+
     return 0
 
 if __name__ == "__main__":

Modified: grass/trunk/scripts/v.db.dropcolumn/v.db.dropcolumn.py
===================================================================
--- grass/trunk/scripts/v.db.dropcolumn/v.db.dropcolumn.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.db.dropcolumn/v.db.dropcolumn.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -5,7 +5,7 @@
 # MODULE:       v.db.dropcolumn
 # AUTHOR(S):    Markus Neteler
 #               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
 #               - Based on v.db.addcolumn
 #               - with special trick for SQLite
@@ -45,43 +45,43 @@
 
 
 def main():
-    map    = options['map']
-    layer  = options['layer']
+    map = options['map']
+    layer = options['layer']
     columns = options['columns'].split(',')
-    
+
     mapset = grass.gisenv()['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)
-    
+
     f = grass.vector_layer_db(map, layer)
-    
+
     table = f['table']
     keycol = f['key']
     database = f['database']
     driver = f['driver']
-    
+
     if not table:
         grass.fatal(_("There is no table connected to the input vector map. "
                       "Unable to delete any column. Exiting."))
-    
+
     if keycol in columns:
         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:
-        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))
             continue
-        
+
         if driver == "sqlite":
             # echo "Using special trick for SQLite"
             # http://www.sqlite.org/faq.html#q11
             colnames = []
             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:
                     continue
                 colnames.append(f[0])
@@ -100,21 +100,21 @@
                 "CREATE UNIQUE INDEX ${table}_cat ON ${table} (${keycol} )",
                 "DROP TABLE ${table}_backup",
                 "COMMIT"
-                ]
+            ]
             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:
             sql = "ALTER TABLE %s DROP COLUMN %s" % (table, column)
 
         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:
             grass.fatal(_("Deleting column failed"))
-    
+
     # write cmd history:
     grass.vector_history(map)
-    
+
 if __name__ == "__main__":
     options, flags = grass.parser()
     main()

Modified: grass/trunk/scripts/v.db.droprow/v.db.droprow.py
===================================================================
--- grass/trunk/scripts/v.db.droprow/v.db.droprow.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.db.droprow/v.db.droprow.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -51,7 +51,7 @@
         return 1
 
     # write cmd history:
-    grass.vector_history(map = options['output'])
+    grass.vector_history(map=options['output'])
 
     return 0
 

Modified: grass/trunk/scripts/v.db.droptable/v.db.droptable.py
===================================================================
--- grass/trunk/scripts/v.db.droptable/v.db.droptable.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.db.droptable/v.db.droptable.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -3,7 +3,7 @@
 ############################################################################
 #
 # MODULE:       v.db.droptable
-# AUTHOR(S):   	Markus Neteler 
+# AUTHOR(S):   	Markus Neteler
 #               Converted to Python by Glynn Clements
 # PURPOSE:      interface to db.execute to drop an existing table of given vector map
 # COPYRIGHT:    (C) 2005, 2008 by the GRASS Development Team
@@ -36,7 +36,7 @@
 
 import sys
 import os
-import grass.script as grass
+import grass.script as gscript
 from grass.exceptions import CalledModuleError
 
 
@@ -47,56 +47,58 @@
     layer = options['layer']
 
     # do some paranoia tests as well:
-    f = grass.vector_layer_db(map, layer)
-    
+    f = gscript.vector_layer_db(map, layer)
+
     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:
-	# 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))
+        # 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 
+    # we use the DB settings selected layer
     database = f['database']
     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:
-	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:
-        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:
-        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
     nuldev = file(os.devnull, 'w')
     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:
-        grass.message(_("(No database links remaining)"))
+        gscript.message(_("(No database links remaining)"))
     else:
-        grass.run_command('v.db.connect', flags='p', map=map)
+        gscript.run_command('v.db.connect', flags='p', map=map)
 
     # write cmd history:
-    grass.vector_history(map)
+    gscript.vector_history(map)
 
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     main()

Modified: grass/trunk/scripts/v.db.join/v.db.join.py
===================================================================
--- grass/trunk/scripts/v.db.join/v.db.join.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.db.join/v.db.join.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -80,7 +80,7 @@
         
     maptable = f['table']
     database = f['database']
-    driver   = f['driver']
+    driver = f['driver']
 
     if driver == 'dbf':
         grass.fatal(_("JOIN is not supported for tables stored in DBF format"))
@@ -89,7 +89,7 @@
         grass.fatal(_("There is no table connected to this map. Unable to join any column."))
 
     # 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,
                                                                 maptable))
 
@@ -157,7 +157,9 @@
                                    otable=otable, ocolumn=ocolumn,
                                    colname=colname)
         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:
             grass.write_command('db.execute', stdin=stmt, input='-',
                                 database=database, driver=driver)

Modified: grass/trunk/scripts/v.db.reconnect.all/v.db.reconnect.all.py
===================================================================
--- grass/trunk/scripts/v.db.reconnect.all/v.db.reconnect.all.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.db.reconnect.all/v.db.reconnect.all.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -53,28 +53,32 @@
 import os
 import string
 
-import grass.script as grass
+import grass.script as gscript
 from grass.exceptions import CalledModuleError
 
 # substitute variables (gisdbase, location_name, mapset)
+
+
 def substitute_db(database):
-    gisenv = grass.gisenv()
+    gisenv = gscript.gisenv()
     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
+
+
 def create_db(driver, database):
     subst_database = substitute_db(database)
     if driver == 'dbf':
         path = subst_database
         # check if destination directory exists
         if not os.path.isdir(path):
-	    # create dbf database
+            # create dbf database
             os.makedirs(path)
-	    return True
+            return True
         return False
 
     if driver == 'sqlite':
@@ -83,77 +87,86 @@
         if not os.path.isdir(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
 
-    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:
-        grass.run_command('db.createdb', driver = driver,
-                          database = subst_database)
+        gscript.run_command('db.createdb', driver=driver,
+                            database=subst_database)
     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
 
 # copy tables if required (-c)
+
+
 def copy_tab(from_driver, from_database, from_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
 
-    grass.info("Copying table <%s> to target database..." % to_table)
+    gscript.info("Copying table <%s> to target database..." % to_table)
     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:
-        grass.fatal(_("Unable to copy table <%s>") % from_table)
+        gscript.fatal(_("Unable to copy table <%s>") % from_table)
 
     return True
 
 # drop tables if required (-d)
+
+
 def drop_tab(vector, layer, table, driver, database):
     # disconnect
     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:
-        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
     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:
-        grass.fatal(_("Unable to drop table <%s>") % table)
+        gscript.fatal(_("Unable to drop table <%s>") % table)
 
 # create index on key column
+
+
 def create_index(driver, database, table, index_name, key):
     if driver == 'dbf':
-	return False
+        return False
 
-    grass.info(_("Creating index <%s>...") % index_name)
+    gscript.info(_("Creating index <%s>...") % index_name)
     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:
-        grass.warning(_("Unable to create index <%s>") % index_name)
+        gscript.warning(_("Unable to create index <%s>") % index_name)
 
+
 def main():
     # old connection
     old_database = options['old_database']
     old_schema = options['old_schema']
     # new connection
-    default_connection = grass.db_connection()
+    default_connection = gscript.db_connection()
     if options['new_driver']:
         new_driver = options['new_driver']
     else:
@@ -168,24 +181,25 @@
         new_schema = default_connection['schema']
 
     if old_database == '':
-    	old_database = None
+        old_database = None
     old_database_subst = 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)
 
     if old_database_subst == new_database_subst and old_schema == new_schema:
-	grass.fatal(_("Old and new database connection is identical. Nothing to do."))
+        gscript.fatal(_("Old and new database connection is identical. "
+                        "Nothing to do."))
 
-    mapset = grass.gisenv()['MAPSET']
+    mapset = gscript.gisenv()['MAPSET']
 
-    vectors = grass.list_grouped('vect')[mapset]
+    vectors = gscript.list_grouped('vect')[mapset]
     num_vectors = len(vectors)
 
     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
     for vect in vectors:
@@ -213,21 +227,22 @@
             else:
                 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
-	    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:
-                grass.verbose(_("Reconnecting layer %d...") % layer)
+                gscript.verbose(_("Reconnecting layer %d...") % layer)
 
                 if flags['c']:
                     # check if table exists in new database
@@ -236,26 +251,34 @@
 
                 # drop original table if required
                 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)
-		# NOTE: v.db.connect creates an index on the key column
+                # NOTE: v.db.connect creates an index on the key column
                 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:
-                    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:
-		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
 
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     nuldev = file(os.devnull, 'w')
     sys.exit(main())

Modified: grass/trunk/scripts/v.db.renamecolumn/v.db.renamecolumn.py
===================================================================
--- grass/trunk/scripts/v.db.renamecolumn/v.db.renamecolumn.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.db.renamecolumn/v.db.renamecolumn.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -5,10 +5,10 @@
 # MODULE:       v.db.renamecolumn
 # AUTHOR(S):    Markus Neteler
 #               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
 #               - 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)
 # COPYRIGHT:    (C) 2007 by the GRASS Development Team
 #
@@ -30,7 +30,7 @@
 #%end
 #%option G_OPT_V_FIELD
 #%end
-#%option 
+#%option
 #% key: column
 #% type: string
 #% description: Old and new name of the column (old,new)
@@ -43,6 +43,7 @@
 import os
 import grass.script as grass
 
+
 def main():
     map = options['map']
     layer = options['layer']
@@ -50,7 +51,7 @@
 
     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)
 
     f = grass.vector_layer_db(map, layer)
@@ -69,10 +70,14 @@
 
     if driver == "dbf":
         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:
-        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
     oldcoltype = None
@@ -93,10 +98,10 @@
         else:
             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)
-        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':
         if oldcoltype.upper() == "CHARACTER":
             newcoltype = "varchar(%s)" % (oldcollength)
@@ -104,10 +109,10 @@
             newcoltype = oldcoltype
 
         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:
         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:
     grass.vector_history(map)

Modified: grass/trunk/scripts/v.db.univar/v.db.univar.py
===================================================================
--- grass/trunk/scripts/v.db.univar/v.db.univar.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.db.univar/v.db.univar.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -53,50 +53,49 @@
 
 import sys
 import os
-import grass.script as grass
+import grass.script as gscript
 from grass.exceptions import CalledModuleError
 
+
 def main():
     global tmp
-    tmp = grass.tempfile()
+    tmp = gscript.tempfile()
 
     vector = options['map']
     layer = options['layer']
     column = options['column']
     where = options['where']
     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:
-        fi = grass.vector_db(vector, stderr = nuldev)[int(layer)]
+        fi = gscript.vector_db(vector, stderr=nuldev)[int(layer)]
     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']
     database = fi['database']
     driver = fi['driver']
-    
+
     passflags = None
     if flags['e']:
-	passflags = 'e'
+        passflags = 'e'
     if flags['g']:
-	if not passflags:
-	    passflags = 'g'
-	else:
-	    passflags = passflags + 'g'
+        if not passflags:
+            passflags = 'g'
+        else:
+            passflags = passflags + 'g'
 
     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:
         sys.exit(1)
-    
+
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gscript.parser()
     nuldev = file(os.devnull, 'w')
     main()

Modified: grass/trunk/scripts/v.db.update/v.db.update.py
===================================================================
--- grass/trunk/scripts/v.db.update/v.db.update.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.db.update/v.db.update.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -54,6 +54,7 @@
 import os
 import grass.script as grass
 
+
 def main():
     vector = options['map']
     layer = options['layer']
@@ -61,18 +62,19 @@
     value = options['value']
     qcolumn = options['query_column']
     where = options['where']
-    sqlitefile  = options['sqliteextra']
+    sqlitefile = options['sqliteextra']
 
     mapset = grass.gisenv()['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)
 
     try:
         f = grass.vector_db(vector)[int(layer)]
     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']
     database = f['database']
@@ -113,7 +115,7 @@
         cmd = sqliteload + 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:
     grass.vector_history(vector)

Modified: grass/trunk/scripts/v.dissolve/v.dissolve.py
===================================================================
--- grass/trunk/scripts/v.dissolve/v.dissolve.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.dissolve/v.dissolve.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -43,8 +43,11 @@
 
 def cleanup():
     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():
     global output, tmp
 
@@ -53,44 +56,45 @@
     layer = options['layer']
     column = options['column']
 
-    #### setup temporary file
+    # setup temporary file
     tmp = str(os.getpid())
 
     # 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:
-        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:
         if int(layer) == -1:
             grass.warning(_("Invalid layer number (%d). "
-                            "Parameter '%s' specified, assuming layer '1'.") % 
+                            "Parameter '%s' specified, assuming layer '1'.") %
                           (int(layer), 'column'))
             layer = '1'
         try:
             coltype = grass.vector_columns(input, layer)[column]
         except KeyError:
             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)
 
-	table = f['table']
+        table = f['table']
 
-	tmpfile = '%s_%s' % (output, tmp)
+        tmpfile = '%s_%s' % (output, tmp)
 
         try:
             grass.run_command('v.reclass', input=input, output=tmpfile,
                               layer=layer, column=column)
             grass.run_command('v.extract', flags='d', input=tmpfile,
                               output=output, type='area', layer=layer)
-        except CalledModuleError, e:
+        except CalledModuleError as e:
             grass.fatal(_("Final extraction steps failed."
                           " Check above error messages and"
                           " see following details:\n%s") % e)

Modified: grass/trunk/scripts/v.import/v.import.py
===================================================================
--- grass/trunk/scripts/v.import/v.import.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.import/v.import.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -153,10 +153,10 @@
         # list datum transform parameters
         if not options['epsg']:
             grass.fatal(_("Missing value for parameter <%s>") % 'epsg')
-        
+
         return grass.run_command('g.proj', epsg=options['epsg'],
                                  datum_trans=options['datum_trans'])
-    
+
     grassenv = grass.gisenv()
     tgtloc = grassenv['LOCATION_NAME']
     tgtmapset = grassenv['MAPSET']
@@ -191,12 +191,12 @@
     # switch to temp location
     os.environ['GISRC'] = str(SRCGISRC)
 
-    if options['epsg']: # force given EPSG
+    if options['epsg']:  # force given EPSG
         kwargs = {}
         if options['datum_trans']:
             kwargs['datum_trans'] = options['datum_trans']
         grass.run_command('g.proj', flags='c', epsg=options['epsg'], **kwargs)
-        
+
     # switch to target location
     os.environ['GISRC'] = str(tgtgisrc)
 
@@ -206,21 +206,25 @@
         try:
             grass.run_command('v.in.ogr', input=OGRdatasource,
                               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
         except CalledModuleError:
             grass.fatal(_("Unable to import <%s>") % OGRdatasource)
 
     # make sure target is not xy
     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
     os.environ['GISRC'] = str(SRCGISRC)
 
     # print projection at verbose level
     grass.verbose(grass.read_command('g.proj', flags='p').rstrip(os.linesep))
-    
+
     # make sure input is not xy
     if grass.parse_command('g.proj', flags='g')['name'] == 'xy_location_unprojected':
         grass.fatal(_("Coordinate reference system not available for input <%s>") % OGRdatasource)

Modified: grass/trunk/scripts/v.in.e00/v.in.e00.py
===================================================================
--- grass/trunk/scripts/v.in.e00/v.in.e00.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.in.e00/v.in.e00.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -43,7 +43,7 @@
 import glob
 from grass.script.utils import try_rmdir, try_remove, basename
 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
 
 
@@ -54,113 +54,115 @@
 
     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.
-    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')
     # avcimport only accepts 13 chars:
     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
     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:
-	name = vect
+        name = vect
     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)
     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:
-	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)
 
-    #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:
-	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+')
 
-    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:
-	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)
+        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:
+    # SQL name fix:
     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:
-        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],
                           output=name)
     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 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.rmdir(tmpdir)
-	
-    #### end
-    grass.message(_("Done."))
 
+    # end
+    gcore.message(_("Done."))
+
     # write cmd history:
     gvect.vector_history(name)
 
 if __name__ == "__main__":
-    options, flags = grass.parser()
+    options, flags = gcore.parser()
     main()
-

Modified: grass/trunk/scripts/v.in.geonames/v.in.geonames.py
===================================================================
--- grass/trunk/scripts/v.in.geonames/v.in.geonames.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.in.geonames/v.in.geonames.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -37,11 +37,12 @@
 import os
 import grass.script as grass
 
+
 def main():
-    infile  = options['input']
+    infile = options['input']
     outfile = options['output']
-    
-    #are we in LatLong location?
+
+    # are we in LatLong location?
     s = grass.read_command("g.proj", flags='j')
     kv = grass.parse_key_val(s)
     if kv['+proj'] != 'longlat':
@@ -55,7 +56,8 @@
     kv = grass.db_connection()
     dbfdriver = kv['driver'] == 'dbf'
     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:
         num_places = sum(1 for _ in f)
@@ -87,55 +89,54 @@
 
     # geonameid|name|asciiname|alternatenames|latitude|longitude|featureclass|featurecode|countrycode|cc2|admin1code|admin2code|admin3code|admin4code|population|elevation|gtopo30|timezone|modificationdate
 
-
     # debug:
     # head -n 3 ${TMPFILE}.csv
 
     # use different column names limited to 10 chars for dbf
     if dbfdriver:
         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:
         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']
+                   '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)
+    grass.run_command('v.in.ascii', cat=0, x=6, y=5, sep='tab',
+                      input=infile, output=outfile,
+                      columns=columns)
 
     # write cmd history:
     grass.vector_history(outfile)
@@ -143,4 +144,3 @@
 if __name__ == "__main__":
     options, flags = grass.parser()
     main()
-

Modified: grass/trunk/scripts/v.in.lines/v.in.lines.py
===================================================================
--- grass/trunk/scripts/v.in.lines/v.in.lines.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.in.lines/v.in.lines.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -41,9 +41,11 @@
 from grass.script.utils import separator, try_remove
 from grass.script import core as grass
 
+
 def cleanup():
     try_remove(tmp)
 
+
 def main():
     global tmp
 
@@ -57,11 +59,9 @@
     else:
         do3D = ''
 
-
     tmp = grass.tempfile()
 
-
-    #### set up input file
+    # set up input file
     if options['input'] == '-':
         infile = None
         inf = sys.stdin
@@ -71,7 +71,6 @@
             grass.fatal(_("Unable to read input file <%s>") % infile)
         grass.debug("input file=[%s]" % infile)
 
-
     if not infile:
         # read from stdin and write to tmpfile (v.in.mapgen wants a real file)
         outf = file(tmp, 'w')
@@ -99,8 +98,7 @@
             outf.close()
             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)
     for line in inf:
         if len(line.lstrip()) == 0 or line[0] == '#':
@@ -111,11 +109,10 @@
     if (do3D and numcols < 3) or (not do3D and numcols < 2):
         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__":
     options, flags = grass.parser()
     atexit.register(cleanup)

Modified: grass/trunk/scripts/v.in.mapgen/v.in.mapgen.py
===================================================================
--- grass/trunk/scripts/v.in.mapgen/v.in.mapgen.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.in.mapgen/v.in.mapgen.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -34,7 +34,7 @@
 #%end
 #%flag
 #% 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
 #%option G_OPT_F_INPUT
 #% description: Name of input file in Mapgen/Matlab format
@@ -59,6 +59,7 @@
     try_remove(tmp)
     try_remove(tmp + '.dig')
 
+
 def main():
     global tmp
 
@@ -89,32 +90,32 @@
 
     tmp = grass.tempfile()
 
-    #### create ascii vector file
+    # create ascii vector file
     inf = file(infile)
     outf = file(tmp, 'w')
 
     grass.message(_("Importing data..."))
-    cat = 1   
+    cat = 1
     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 }
         #    $1~/\d*/   { printf("L %d\n", R) }
         #    $1~/   .*/ { printf(" %lf %lf\n", $2, $1) ; ++R }
         #    $1~/END/   { }' | tac > "$TMP"
 
-        ## matlab format.
+        # matlab format.
         points = []
- 
+
         for line in inf:
             f = line.split()
             if f[0].lower() == 'nan':
                 if points != []:
                     outf.write("L %d 1\n" % len(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)
                     cat += 1
                 points = []
@@ -122,7 +123,7 @@
                 if len(f) == 2:
                     f.append('0')
                 points.append(f)
-        
+
         if points != []:
             outf.write("L %d 1\n" % len(points))
             for point in points:
@@ -131,36 +132,36 @@
                 except ValueError:
                     grass.fatal(_("An error occurred on line '%s', exiting.") % line.strip())
             outf.write(" 1 %d\n" % cat)
-            cat += 1       
+            cat += 1
     else:
-        ## mapgen format.
+        # mapgen format.
         points = []
         for line in inf:
             if line[0] == '#':
                 if points != []:
                     outf.write("L %d 1\n" % len(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)
                     cat += 1
                 points = []
             else:
                 points.append(line.rstrip('\r\n').split('\t'))
-        
+
         if points != []:
             outf.write("L %d 1\n" % len(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)
             cat += 1
     outf.close()
     inf.close()
 
-    #### create digit header
+    # create digit header
     digfile = tmp + '.dig'
     outf = file(digfile, 'w')
-    t = string.Template(\
-"""ORGANIZATION: GRASSroots organization
+    t = string.Template(
+        """ORGANIZATION: GRASSroots organization
 DIGIT DATE:   $date
 DIGIT NAME:   $user@$host
 MAP NAME:     $name
@@ -175,12 +176,12 @@
     year = time.strftime("%Y")
     user = os.getenv('USERNAME') or os.getenv('LOGNAME')
     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)
-    
-    #### process points list to ascii vector file (merge in vertices)
+
+    # process points list to ascii vector file (merge in vertices)
     inf = file(tmp)
     shutil.copyfileobj(inf, outf)
     inf.close()
@@ -188,13 +189,13 @@
     outf.close()
 
     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)
         shutil.copyfileobj(inf, sys.stdout)
         inf.close()
     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:
             grass.run_command('v.in.ascii', flags=do3D, input=digfile,
                               output=name, format='standard')
@@ -205,4 +206,3 @@
     options, flags = grass.parser()
     atexit.register(cleanup)
     main()
-

Modified: grass/trunk/scripts/v.in.wfs/v.in.wfs.py
===================================================================
--- grass/trunk/scripts/v.in.wfs/v.in.wfs.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.in.wfs/v.in.wfs.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -64,7 +64,7 @@
 #%end
 #%flag
 #% 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
 #% suppress_required: yes
 #%end
@@ -83,6 +83,7 @@
 except ImportError:
     from urllib.request import urlopen
 
+
 def main():
     out = options['output']
     wfs_url = options['url']
@@ -107,7 +108,7 @@
             grass.fatal('Features begin with index "1"')
 
     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
 
     if flags['l']:
@@ -122,10 +123,10 @@
     inf = urlopen(wfs_url)
     outf = file(tmpxml, 'wb')
     while True:
-	s = inf.read()
-	if not s:
-	    break
-	outf.write(s)
+        s = inf.read()
+        if not s:
+            break
+        outf.write(s)
     inf.close()
     outf.close()
 
@@ -138,7 +139,6 @@
         try_remove(tmpxml)
         sys.exit(0)
 
-
     grass.message(_("Importing data..."))
     try:
         grass.run_command('v.in.ogr', flags='o', input=tmpxml, output=out)

Modified: grass/trunk/scripts/v.krige/v.krige.py
===================================================================
--- grass/trunk/scripts/v.krige/v.krige.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.krige/v.krige.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -15,7 +15,7 @@
 for details.
 """
 
-## g.parser information
+# g.parser information
 
 #%module
 #% description: Performs ordinary or block kriging for vector maps.
@@ -96,27 +96,26 @@
 #% description: If omitted, will be <input name>_kriging.var
 #% required : no
 #%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)
 
-### 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
 try:
     import grass.script as grass
 except ImportError:
     sys.exit(_("No GRASS-python library found"))
-    
+
 # move other checks in functions, as R?
 
 # globals
@@ -128,12 +127,15 @@
 #~ robjects = 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:
     """ Executes analysis. For the moment, only with gstat functions."""
     # moved here the global variables
+
     def __init__(self):
         #~ self.Command = None
         self.InputData = None
@@ -141,24 +143,24 @@
         #~ VariogramFunction = None
         #~ robjects = None
         #~ rinterface = None
-    
+
     def ImportMap(self, map, column):
         """ 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."""
 
         #@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,
         # 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
             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 is done on row.names
             Rpointmap = robjects.r.spCbind(Rpointmap, coordinatesDF)
-            
+
         # GRASS checks for null values in the chosen column. R can hardly handle column as a variable,
         # looks for a hardcoded string.
         cols = grass.vector_columns(map=map, layer=1)
@@ -166,95 +168,101 @@
                                         map=map,
                                         column=column,
                                         type='point',
-                                        parse = (grass.parse_key_val,
-                                                 {'sep':': '}
-                                                 )
+                                        parse=(grass.parse_key_val,
+                                               {'sep': ': '}
+                                               )
                                         )['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
-    
+
     def CreateGrid(self, inputdata):
         Region = grass.region()
         Grid = robjects.r.gmeta2grd()
 
         # addition of coordinates columns into dataframe.
         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
-    
+
     def ComposeFormula(self, column, isblock):
         if isblock is True:
             predictor = 'x+y'
         else:
             predictor = '1'
-        print column + "~" + predictor
+        print(column + "~" + predictor)
         Formula = robjects.Formula(column + "~" + predictor)
         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.
         Returns a list containing data and model variograms. """
-        
+
         Variograms = {}
-        
+
         if model is '':
             robjects.r.require('automap')
             DottedParams = {}
             #print (nugget.r_repr(), sill, range)
             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
                 VariogramModel = robjects.r.autofitVariogram(formula, inputdata, **DottedParams)
             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['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]
             Variograms['model'] = ModelDF.levels[ModelDF[1] - 1]
         else:
             DataVariogram = robjects.r['variogram'](formula, inputdata)
             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['variogrammodel'] = VariogramModel
             Variograms['model'] = model
         return Variograms
-    
+
     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
-        #print DottedParams
+        # print DottedParams
         KrigingResult = robjects.r.krige(formula, inputdata, grid, model, **DottedParams)
         return KrigingResult
- 
+
     def ExportMap(self, map, column, name, overwrite, command, variograms):
         # 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',
-                          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):
         """ Wrapper for all functions above. """
 
@@ -267,9 +275,9 @@
         # and from here over, InputData refers to the global variable
         #print(robjects.r.slot(InputData, 'data').names)
         logger.message(_("Data successfully imported."))
-        
+
         GridPredicted = self.CreateGrid(self.InputData)
-        
+
         logger.message(_("Fitting variogram..."))
 
         if block is not '':
@@ -278,87 +286,93 @@
             self.predictor = '1'
         if self.Variogram is None:
             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(_("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."))
-        
-        self.ExportMap(map = KrigingResult,
+
+        self.ExportMap(map=KrigingResult,
                        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 '':
-            self.ExportMap(map = KrigingResult,
+            self.ExportMap(map=KrigingResult,
                            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. """
     #@FIXME: solve this double ifelse. the control should not be done twice.
-    
+
     controller = Controller()
-    
+
     if argv is None:
         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
         if not os.getenv("GRASS_WXBUNDLED"):
             from core import globalvar
             globalvar.CheckForWx()
         from modules import vkrige as GUI
-        
+
         import wx
-        
+
         app = wx.App()
-        KrigingFrame = GUI.KrigingModule(parent = None,
-                                         Rinstance = robjects,
-                                         controller = controller)
+        KrigingFrame = GUI.KrigingModule(parent=None,
+                                         Rinstance=robjects,
+                                         controller=controller)
         KrigingFrame.Centre()
         KrigingFrame.Show()
         app.MainLoop()
-        
+
     else:
-        #CLI
+        # CLI
         options, flags = argv
-        
+
         #@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.
-        
+
         # create output map name, if not specified
         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]
             except:
                 pass
             options['output'] = options['input'] + '_kriging'
 
         # 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."))
 
         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."))
 
-        importR()        
+        importR()
         if options['model'] is '':
             try:
                 robjects.r.require("automap")
@@ -366,19 +380,20 @@
                 grass.fatal(_("R package automap is missing, no variogram autofit available."))
         else:
             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.
-        #print grass.write_command(argv)
+        # print grass.write_command(argv)
         command = ""
         notnulloptions = {}
         for k, v in options.items():
             if v is not '':
                 notnulloptions[k] = v
         command = command.join("%s=%s " % (k, v) for k, v in notnulloptions.items())
-        
+
         # 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 each == "kappa":
                     options[each] = float(options[each])
@@ -386,23 +401,24 @@
                     options[each] = int(options[each])
             else:
                 options[each] = robjects.r('''NA''')
-        
+
         #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():
     # R
     # unuseful since rpy2 will complain adequately.
@@ -411,31 +427,31 @@
     #    grass.find_program('R')
     # except:
     #    sys.exit(_("R is not installed. Install it and re-run, or modify environment variables."))
-    
+
     # rpy2
     global robjects
     global rinterface
     grass.message(_('Loading dependencies, please wait...'))
     try:
         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:
         # ok for other OSes?
         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.
     missingPackagesList = []
     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)
     if missingPackagesList:
         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)
-    
+
 if __name__ == '__main__':
     if len(sys.argv) > 1:
-        sys.exit(main(argv = grass.parser()))
+        sys.exit(main(argv=grass.parser()))
     else:
         main()

Modified: grass/trunk/scripts/v.pack/v.pack.py
===================================================================
--- grass/trunk/scripts/v.pack/v.pack.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.pack/v.pack.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -43,9 +43,11 @@
 from grass.script import core as grass
 from grass.script import vector as vector
 
+
 def cleanup():
     try_rmdir(basedir)
 
+
 def main():
     infile = options['input']
     compression_off = flags['c']
@@ -54,14 +56,14 @@
     basedir = grass.tempdir()
 
     # check if vector map exists
-    gfile = grass.find_file(infile, element = 'vector')
+    gfile = grass.find_file(infile, element='vector')
     if not gfile['name']:
         grass.fatal(_("Vector map <%s> not found") % infile)
 
     # check if input vector map is in the native format
     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
     if infile.find('@'):
@@ -86,9 +88,9 @@
 
     # write tar file, optional compression
     if compression_off:
-        tar = tarfile.open(name = outfile, mode = 'w:')
+        tar = tarfile.open(name=outfile, mode='w:')
     else:
-        tar = tarfile.open(name = outfile, mode = 'w:gz')
+        tar = tarfile.open(name=outfile, mode='w:gz')
     tar.add(gfile['file'], infile)
 
     # check if exist a db connection for the vector

Modified: grass/trunk/scripts/v.rast.stats/testsuite/test_v_rast_stats.py
===================================================================
--- grass/trunk/scripts/v.rast.stats/testsuite/test_v_rast_stats.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.rast.stats/testsuite/test_v_rast_stats.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -5,6 +5,7 @@
 from grass.gunittest.case import TestCase
 from grass.gunittest.gmodules import SimpleModule
 
+
 class TestRastStats(TestCase):
 
     @classmethod
@@ -36,19 +37,20 @@
 
     def test_1(self):
         # 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
 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")
         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)
 
+
 class TestRastStatsFails(TestCase):
 
     def test_error_handling_a(self):
@@ -60,7 +62,7 @@
         # No raster map
         self.assertModuleFail("v.rast.stats", map="zone_map",
                               column_prefix="a")
-        
+
     def test_error_handling_d(self):
         # No column_prefix
         self.assertModuleFail("v.rast.stats", map="zone_map", raster="map_b")
@@ -68,5 +70,3 @@
 if __name__ == '__main__':
     from grass.gunittest.main import test
     test()
-
-

Modified: grass/trunk/scripts/v.rast.stats/v.rast.stats.py
===================================================================
--- grass/trunk/scripts/v.rast.stats/v.rast.stats.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.rast.stats/v.rast.stats.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -79,7 +79,7 @@
 def main():
     global tmp, sqltmp, tmpname, nuldev, vector, rastertmp
     rastertmp = False
-    #### setup temporary files
+    # setup temporary files
     tmp = grass.tempfile()
     sqltmp = tmp + ".sql"
     # we need a random name
@@ -146,13 +146,15 @@
     try:
         fi = grass.vector_db(map=vector)[int(layer)]
     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:
     dbfdriver = fi['driver'] == 'dbf'
 
     # Find out which table is linked to the vector map on the given layer
     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
     #basecols = ['n', 'min', 'max', 'range', 'mean', 'stddev', 'variance', 'cf_var', 'sum']
@@ -206,7 +208,7 @@
         if currcolumn in grass.vector_columns(vector, layer).keys():
             if not flags['c']:
                 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:
             if i == "n":
                 coltype = "INTEGER"
@@ -277,7 +279,9 @@
                          " of vector map <{vector}>."
                          ).format(raster=raster, vector=vector)))
     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
 
     sys.exit(exitcode)

Modified: grass/trunk/scripts/v.report/v.report.py
===================================================================
--- grass/trunk/scripts/v.report/v.report.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.report/v.report.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -47,6 +47,7 @@
 import os
 import grass.script as grass
 
+
 def uniq(l):
     result = []
     last = None
@@ -56,6 +57,7 @@
             last = i
     return result
 
+
 def main():
     mapname = options['map']
     option = options['option']
@@ -75,13 +77,13 @@
         colnames = ['cat']
 
     if option == 'coor':
-        columns = ['dummy1','dummy2','dummy3']
-        extracolnames = ['x','y','z']
+        columns = ['dummy1', 'dummy2', 'dummy3']
+        extracolnames = ['x', 'y', 'z']
     else:
         columns = ['dummy1']
         extracolnames = [option]
 
-    if units in ['p','percent']:
+    if units in ['p', 'percent']:
         unitsp = 'meters'
     elif units:
         unitsp = units
@@ -90,7 +92,7 @@
 
     # NOTE: we suppress -1 cat and 0 cat
     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 = []
         for line in p.stdout:
             cols = line.rstrip('\r\n').split('|')
@@ -100,23 +102,23 @@
         p.wait()
         if p.returncode != 0:
             sys.exit(1)
-        
+
         records1.sort()
 
         if len(records1) == 0:
             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"
                               "there are no categories present in the key column '%s'. Consider using"
                               "v.to.db to correct this.") % (mapname, f['key']))
             except KeyError:
                 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 = []
         for line in p.stdout:
             fields = line.rstrip('\r\n').split('|')
@@ -126,7 +128,7 @@
         p.wait()
         records2.sort()
 
-        #make pre-table
+        # make pre-table
         # len(records1) may not be the same as len(records2) because
         # v.db.select can return attributes that are not linked to features.
         records3 = []
@@ -134,7 +136,7 @@
             records3.append(filter(lambda r1: r1[0] == r2[0], records1)[0] + r2[1:])
     else:
         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:
             field = int(line.rstrip())
             if field > 0:
@@ -143,11 +145,11 @@
         records1.sort()
         records1 = uniq(records1)
 
-        #make pre-table
-        p = grass.pipe_command('v.to.db', flags = 'p',
-                               quiet = True,
-                               map = mapname, option = option, columns = columns,
-                               layer = layer, units = unitsp)
+        # make pre-table
+        p = grass.pipe_command('v.to.db', flags='p',
+                               quiet=True,
+                               map=mapname, option=option, columns=columns,
+                               layer=layer, units=unitsp)
         records3 = []
         for line in p.stdout:
             fields = line.rstrip('\r\n').split('|')
@@ -160,11 +162,11 @@
     # print table header
     sys.stdout.write('|'.join(colnames + extracolnames) + '\n')
 
-    #make and print the table:
+    # make and print the table:
     numcols = len(colnames) + len(extracolnames)
 
     # calculate percents if requested
-    if units != '' and units in ['p','percent']:
+    if units != '' and units in ['p', 'percent']:
         # calculate total area value
         areatot = 0
         for r in records3:
@@ -177,12 +179,12 @@
     # sort results
     if options['sort']:
         if options['sort'] == 'asc':
-            records3.sort(key = lambda r: r[-1])
+            records3.sort(key=lambda r: r[-1])
         else:
-            records3.sort(key = lambda r: r[-1], reverse = True)
-    
+            records3.sort(key=lambda r: r[-1], reverse=True)
+
     for r in records3:
-        sys.stdout.write('|'.join(map(str,r)) + '\n')
+        sys.stdout.write('|'.join(map(str, r)) + '\n')
 
 if __name__ == "__main__":
     options, flags = grass.parser()

Modified: grass/trunk/scripts/v.unpack/v.unpack.py
===================================================================
--- grass/trunk/scripts/v.unpack/v.unpack.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.unpack/v.unpack.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -116,7 +116,8 @@
     skip_projection_check = False
     if not os.path.exists(os.path.join(tmp_dir, 'PROJ_INFO')):
         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
 
     if not skip_projection_check:
@@ -124,14 +125,14 @@
         if not grass.compare_key_value_text_files(filename_a=os.path.join(tmp_dir, 'PROJ_INFO'),
                                                   filename_b=loc_proj, proj=True):
             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'),
                                                   filename_b=loc_proj_units,
                                                   units=True):
             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 flags['o']:
                 grass.warning(_("Projection information does not match. Proceeding..."))
@@ -167,7 +168,7 @@
         # check if dbf or sqlite directory exists
         if dbconn['driver'] == 'dbf' and not os.path.exists(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'))
         # for each old connection
         for t in dbnlist:

Modified: grass/trunk/scripts/v.what.strds/testsuite/test_what_strds.py
===================================================================
--- grass/trunk/scripts/v.what.strds/testsuite/test_what_strds.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.what.strds/testsuite/test_what_strds.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -21,12 +21,12 @@
         """Initiate the temporal GIS and set the 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,
                       overwrite=True)

Modified: grass/trunk/scripts/v.what.strds/v.what.strds.py
===================================================================
--- grass/trunk/scripts/v.what.strds/v.what.strds.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/v.what.strds/v.what.strds.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -60,6 +60,7 @@
 
 
 class Sample(object):
+
     def __init__(self, start=None, end=None, raster_names=None,
                  strds_name=None):
         self.start = start
@@ -151,9 +152,9 @@
                               "datasets must be equal\n<%(a)s> of type "
                               "%(type_a)s do not match <%(b)s> of type "
                               "%(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",
                                                         strds_names,

Modified: grass/trunk/scripts/wxpyimgview/wxpyimgview.py
===================================================================
--- grass/trunk/scripts/wxpyimgview/wxpyimgview.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/wxpyimgview/wxpyimgview.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -16,7 +16,7 @@
 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 #  GNU General Public License for more details.
 #
-#############################################################################/
+# /
 
 #%module
 #% description: Views BMP images from the PNG driver.
@@ -43,7 +43,7 @@
 
 if __name__ == "__main__":
     options, flags = grass.parser()
-    image   = options['image']
+    image = options['image']
     percent = options['percent']
     python = os.getenv('GRASS_PYTHON', 'python')
     gisbase = os.environ['GISBASE']

Modified: grass/trunk/scripts/wxpyimgview/wxpyimgview_gui.py
===================================================================
--- grass/trunk/scripts/wxpyimgview/wxpyimgview_gui.py	2016-05-02 16:09:16 UTC (rev 68363)
+++ grass/trunk/scripts/wxpyimgview/wxpyimgview_gui.py	2016-05-02 16:11:41 UTC (rev 68364)
@@ -16,7 +16,7 @@
 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 #  GNU General Public License for more details.
 #
-#############################################################################/
+# /
 
 #%module
 #% description: Views BMP images from the PNG driver.
@@ -46,124 +46,127 @@
 wxversion.select('2.8')
 import wx
 
+
 class Frame(wx.Frame):
     title = "Image Viewer"
 
     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):
-	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):
-	ev.GetDC();
+        ev.GetDC()
 
     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):
-	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):
-	self.Refresh()
+        self.Refresh()
 
     def dummy(self, ev):
-	pass
+        pass
 
+
 class Application(wx.App):
+
     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):
-	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):
-	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):
-	wx.CallAfter(self.mainwin.Refresh);
+        wx.CallAfter(self.mainwin.Refresh)
 
     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):
-	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__":
     app = Application()



More information about the grass-commit mailing list