Procházet zdrojové kódy

Add support for python2 code and python3

git-svn-id: https://svn.osgeo.org/grass/grass/trunk@59127 15284696-431f-4ddb-bdfa-cd5b030d7da7
Pietro Zambelli před 11 roky
rodič
revize
c31d7c7fda
35 změnil soubory, kde provedl 326 přidání a 279 odebrání
  1. 8 8
      lib/python/pygrass/__init__.py
  2. 5 4
      lib/python/pygrass/errors.py
  3. 5 3
      lib/python/pygrass/functions.py
  4. 4 2
      lib/python/pygrass/gis/__init__.py
  5. 2 0
      lib/python/pygrass/gis/region.py
  6. 2 2
      lib/python/pygrass/messages/__init__.py
  7. 5 5
      lib/python/pygrass/modules/__init__.py
  8. 5 4
      lib/python/pygrass/modules/grid/__init__.py
  9. 3 1
      lib/python/pygrass/modules/grid/grid.py
  10. 3 1
      lib/python/pygrass/modules/grid/patch.py
  11. 6 4
      lib/python/pygrass/modules/grid/split.py
  12. 6 6
      lib/python/pygrass/modules/interface/__init__.py
  13. 3 1
      lib/python/pygrass/modules/interface/flag.py
  14. 22 13
      lib/python/pygrass/modules/interface/module.py
  15. 5 4
      lib/python/pygrass/modules/interface/parameter.py
  16. 2 1
      lib/python/pygrass/modules/interface/read.py
  17. 3 1
      lib/python/pygrass/modules/interface/typedict.py
  18. 3 2
      lib/python/pygrass/modules/shortcuts.py
  19. 43 54
      lib/python/pygrass/raster/__init__.py
  20. 19 13
      lib/python/pygrass/raster/abstract.py
  21. 1 1
      lib/python/pygrass/raster/buffer.py
  22. 23 35
      lib/python/pygrass/raster/category.py
  23. 32 17
      lib/python/pygrass/raster/history.py
  24. 1 1
      lib/python/pygrass/raster/rowio.py
  25. 1 1
      lib/python/pygrass/raster/segment.py
  26. 2 2
      lib/python/pygrass/shell/__init__.py
  27. 38 35
      lib/python/pygrass/tests/benchmark.py
  28. 11 8
      lib/python/pygrass/tests/set_mapset.py
  29. 18 14
      lib/python/pygrass/vector/__init__.py
  30. 5 7
      lib/python/pygrass/vector/abstract.py
  31. 7 7
      lib/python/pygrass/vector/basic.py
  32. 3 3
      lib/python/pygrass/vector/find.py
  33. 11 8
      lib/python/pygrass/vector/geometry.py
  34. 18 10
      lib/python/pygrass/vector/table.py
  35. 1 1
      lib/python/pygrass/vector/vector_type.py

+ 8 - 8
lib/python/pygrass/__init__.py

@@ -9,11 +9,11 @@ _libgis.G_gisinit('')
 import os as _os
 import os as _os
 import sys as _sys
 import sys as _sys
 
 
-import errors
-import gis
-import functions
-import raster
-import vector
-import modules
-import shell
-import messages
+from . import errors
+from . import gis
+from . import functions
+from . import raster
+from . import vector
+from . import modules
+from . import shell
+from . import messages

+ 5 - 4
lib/python/pygrass/errors.py

@@ -4,8 +4,8 @@ Created on Wed Aug 15 17:33:27 2012
 
 
 @author: pietro
 @author: pietro
 """
 """
-
-from grass.script import warning
+from functools import wraps
+from grass.pygrass.messages import get_msgr
 
 
 
 
 class AbstractError(Exception):
 class AbstractError(Exception):
@@ -37,10 +37,11 @@ class OpenError(AbstractError):
 
 
 
 
 def must_be_open(method):
 def must_be_open(method):
+
+    @wraps(method)
     def wrapper(self, *args, **kargs):
     def wrapper(self, *args, **kargs):
         if self.is_open():
         if self.is_open():
             return method(self, *args, **kargs)
             return method(self, *args, **kargs)
         else:
         else:
-            warning(_("The map is close!"))
-    wrapper.__doc__ = method.__doc__
+            get_msgr().warning(_("The map is close!"))
     return wrapper
     return wrapper

+ 5 - 3
lib/python/pygrass/functions.py

@@ -160,13 +160,13 @@ def is_clean_name(name):
     """
     """
     if name[0].isdigit():
     if name[0].isdigit():
         return False
         return False
-    for char in ' @#^?°,;%&/':
+    for char in u' @#^?°,;%&/':
         if name.find(char) != -1:
         if name.find(char) != -1:
             return False
             return False
     return True
     return True
 
 
 
 
-def coor2pixel((east, north), region):
+def coor2pixel(coord, region):
     """Convert coordinates into a pixel row and col ::
     """Convert coordinates into a pixel row and col ::
 
 
         >>> reg = Region()
         >>> reg = Region()
@@ -175,11 +175,12 @@ def coor2pixel((east, north), region):
         >>> coor2pixel((reg.east, reg.south), reg) == (reg.rows, reg.cols)
         >>> coor2pixel((reg.east, reg.south), reg) == (reg.rows, reg.cols)
         True
         True
     """
     """
+    (east, north) = coord
     return (libraster.Rast_northing_to_row(north, region.c_region),
     return (libraster.Rast_northing_to_row(north, region.c_region),
             libraster.Rast_easting_to_col(east, region.c_region))
             libraster.Rast_easting_to_col(east, region.c_region))
 
 
 
 
-def pixel2coor((col, row), region):
+def pixel2coor(pixel, region):
     """Convert row and col of a pixel into a coordinates ::
     """Convert row and col of a pixel into a coordinates ::
 
 
         >>> reg = Region()
         >>> reg = Region()
@@ -188,6 +189,7 @@ def pixel2coor((col, row), region):
         >>> pixel2coor((reg.cols, reg.rows), reg) == (reg.south, reg.east)
         >>> pixel2coor((reg.cols, reg.rows), reg) == (reg.south, reg.east)
         True
         True
     """
     """
+    (col, row) = pixel
     return (libraster.Rast_row_to_northing(row, region.c_region),
     return (libraster.Rast_row_to_northing(row, region.c_region),
             libraster.Rast_col_to_easting(col, region.c_region))
             libraster.Rast_col_to_easting(col, region.c_region))
 
 

+ 4 - 2
lib/python/pygrass/gis/__init__.py

@@ -1,6 +1,8 @@
 # -*- coding: utf-8 -*-
 # -*- coding: utf-8 -*-
 #!/usr/bin/env python2.7
 #!/usr/bin/env python2.7
-from __future__ import print_function
+
+from __future__ import (nested_scopes, generators, division, absolute_import,
+                        with_statement, print_function, unicode_literals)
 from os import listdir
 from os import listdir
 from os.path import join, exists, isdir
 from os.path import join, exists, isdir
 import shutil
 import shutil
@@ -23,7 +25,7 @@ script.gisenv()
 import grass.lib.gis as libgis
 import grass.lib.gis as libgis
 from grass.pygrass.functions import getenv
 from grass.pygrass.functions import getenv
 from grass.pygrass.errors import GrassError
 from grass.pygrass.errors import GrassError
-import region
+from . import region
 
 
 
 
 #write dec to check if user have permissions or not
 #write dec to check if user have permissions or not

+ 2 - 0
lib/python/pygrass/gis/region.py

@@ -4,6 +4,8 @@ Created on Fri May 25 12:57:10 2012
 
 
 @author: Pietro Zambelli
 @author: Pietro Zambelli
 """
 """
+from __future__ import (nested_scopes, generators, division, absolute_import,
+                        with_statement, print_function, unicode_literals)
 import ctypes
 import ctypes
 import grass.lib.gis as libgis
 import grass.lib.gis as libgis
 import grass.script as grass
 import grass.script as grass

+ 2 - 2
lib/python/pygrass/messages/__init__.py

@@ -317,7 +317,7 @@ class Messenger(object):
         time.sleep(1)
         time.sleep(1)
 
 
 
 
-def get_msgr(_instance=[None, ], raise_on_error=False):
+def get_msgr(_instance=[None, ], *args, **kwargs):
     """!Return a Messenger instance.
     """!Return a Messenger instance.
 
 
     @return the Messenger instance.
     @return the Messenger instance.
@@ -332,7 +332,7 @@ def get_msgr(_instance=[None, ], raise_on_error=False):
         False
         False
     """
     """
     if not _instance[0]:
     if not _instance[0]:
-        _instance[0] = Messenger(raise_on_error)
+        _instance[0] = Messenger(*args, **kwargs)
     return _instance[0]
     return _instance[0]
 
 
 
 

+ 5 - 5
lib/python/pygrass/modules/__init__.py

@@ -5,10 +5,10 @@ Created on Thu Jul 12 10:23:15 2012
 @author: pietro
 @author: pietro
 
 
 """
 """
-import interface
-from interface import Module, ParallelModuleQueue
+from . import interface
+from .interface import Module, ParallelModuleQueue
 
 
-import grid
-from grid.grid import GridModule
+from . import grid
+from .grid.grid import GridModule
 
 
-import shortcuts
+from . import shortcuts

+ 5 - 4
lib/python/pygrass/modules/grid/__init__.py

@@ -4,7 +4,8 @@ Created on Wed Apr  3 10:41:30 2013
 
 
 @author: pietro
 @author: pietro
 """
 """
-import split
-import patch
-import grid
-from grid import GridModule
+from . import split
+from . import patch
+from . import grid
+from .grid import GridModule
+

+ 3 - 1
lib/python/pygrass/modules/grid/grid.py

@@ -4,6 +4,8 @@ Created on Thu Mar 28 11:06:00 2013
 
 
 @author: pietro
 @author: pietro
 """
 """
+from __future__ import (nested_scopes, generators, division, absolute_import,
+                        with_statement, print_function, unicode_literals)
 import os
 import os
 import multiprocessing as mltp
 import multiprocessing as mltp
 import subprocess as sub
 import subprocess as sub
@@ -434,7 +436,7 @@ def cmd_exe(args):
     else:
     else:
         # set the computational region
         # set the computational region
         lcmd = ['g.region', ]
         lcmd = ['g.region', ]
-        lcmd.extend(["%s=%s" % (k, v) for k, v in bbox.iteritems()])
+        lcmd.extend(["%s=%s" % (k, v) for k, v in bbox.items()])
         sub.Popen(lcmd, env=env).wait()
         sub.Popen(lcmd, env=env).wait()
     if groups:
     if groups:
         copy_groups(groups, gisrc_src, gisrc_dst)
         copy_groups(groups, gisrc_src, gisrc_dst)

+ 3 - 1
lib/python/pygrass/modules/grid/patch.py

@@ -4,6 +4,8 @@ Created on Tue Apr  2 18:57:42 2013
 
 
 @author: pietro
 @author: pietro
 """
 """
+from __future__ import (nested_scopes, generators, division, absolute_import,
+                        with_statement, print_function, unicode_literals)
 from grass.pygrass.gis.region import Region
 from grass.pygrass.gis.region import Region
 from grass.pygrass.raster import RasterRow
 from grass.pygrass.raster import RasterRow
 from grass.pygrass.functions import coor2pixel
 from grass.pygrass.functions import coor2pixel
@@ -29,7 +31,7 @@ def rpatch_row(rast, rasts, bboxes):
     buff = rasts[0][0]
     buff = rasts[0][0]
     rbuff = rasts[0][0]
     rbuff = rasts[0][0]
     r_start, r_end, c_start, c_end = sei[0]
     r_start, r_end, c_start, c_end = sei[0]
-    for row in xrange(r_start, r_end):
+    for row in range(r_start, r_end):
         for col, ras in enumerate(rasts):
         for col, ras in enumerate(rasts):
             r_start, r_end, c_start, c_end = sei[col]
             r_start, r_end, c_start, c_end = sei[col]
             buff = ras.get_row(row, buff)
             buff = ras.get_row(row, buff)

+ 6 - 4
lib/python/pygrass/modules/grid/split.py

@@ -4,6 +4,8 @@ Created on Tue Apr  2 19:00:15 2013
 
 
 @author: pietro
 @author: pietro
 """
 """
+from __future__ import (nested_scopes, generators, division, absolute_import,
+                        with_statement, print_function, unicode_literals)
 from grass.pygrass.gis.region import Region
 from grass.pygrass.gis.region import Region
 from grass.pygrass.vector.basic import Bbox
 from grass.pygrass.vector.basic import Bbox
 
 
@@ -46,9 +48,9 @@ def split_region_tiles(region=None, width=100, height=100, overlap=0):
     nrows = (reg.rows + height - 1) // height
     nrows = (reg.rows + height - 1) // height
     box_list = []
     box_list = []
     #print reg
     #print reg
-    for row in xrange(nrows):
+    for row in range(nrows):
         row_list = []
         row_list = []
-        for col in xrange(ncols):
+        for col in range(ncols):
             #print 'c', c, 'r', r
             #print 'c', c, 'r', r
             row_list.append(get_bbox(reg, row, col, width, height, overlap))
             row_list.append(get_bbox(reg, row, col, width, height, overlap))
         box_list.append(row_list)
         box_list.append(row_list)
@@ -81,9 +83,9 @@ def get_overlap_region_tiles(region=None, width=100, height=100, overlap=0):
     nrows = (reg.rows + height - 1) // height
     nrows = (reg.rows + height - 1) // height
     box_list = []
     box_list = []
     #print reg
     #print reg
-    for row in xrange(nrows):
+    for row in range(nrows):
         row_list = []
         row_list = []
-        for col in xrange(ncols):
+        for col in range(ncols):
             #print 'c', c, 'r', r
             #print 'c', c, 'r', r
             row_list.append(get_bbox(reg, row, col, width, height, -overlap))
             row_list.append(get_bbox(reg, row, col, width, height, -overlap))
         box_list.append(row_list)
         box_list.append(row_list)

+ 6 - 6
lib/python/pygrass/modules/interface/__init__.py

@@ -4,10 +4,10 @@ Created on Tue Apr  2 18:40:39 2013
 
 
 @author: pietro
 @author: pietro
 """
 """
-import flag
-import parameter
-import module
-import typedict
-import read
+from . import flag
+from . import parameter
+from . import module
+from . import typedict
+from . import read
 
 
-from module import Module, ParallelModuleQueue
+from .module import Module, ParallelModuleQueue

+ 3 - 1
lib/python/pygrass/modules/interface/flag.py

@@ -4,7 +4,9 @@ Created on Tue Apr  2 18:39:21 2013
 
 
 @author: pietro
 @author: pietro
 """
 """
-import read
+from __future__ import (nested_scopes, generators, division, absolute_import,
+                        with_statement, print_function, unicode_literals)
+from . import read
 
 
 
 
 class Flag(object):
 class Flag(object):

+ 22 - 13
lib/python/pygrass/modules/interface/module.py

@@ -47,18 +47,23 @@ Created on Tue Apr  2 18:41:27 2013
 
 
 @endcode
 @endcode
 """
 """
-
-from __future__ import print_function
-from itertools import izip_longest
+from __future__ import (nested_scopes, generators, division, absolute_import,
+                        with_statement, print_function, unicode_literals)
+import sys
+
+if sys.version_info.major == 2:
+    from itertools import izip_longest as zip_longest
+else:
+    from itertools import zip_longest
 from xml.etree.ElementTree import fromstring
 from xml.etree.ElementTree import fromstring
 import time
 import time
 
 
 from grass.script.core import Popen, PIPE
 from grass.script.core import Popen, PIPE
 from grass.pygrass.errors import GrassError, ParameterError
 from grass.pygrass.errors import GrassError, ParameterError
-from parameter import Parameter
-from flag import Flag
-from typedict import TypeDict
-from read import GETFROMTAG, DOC
+from .parameter import Parameter
+from .flag import Flag
+from .typedict import TypeDict
+from .read import GETFROMTAG, DOC
 
 
 
 
 class ParallelModuleQueue(object):
 class ParallelModuleQueue(object):
@@ -362,7 +367,7 @@ class Module(object):
                         (k in self.outputs and self.outputs[k].value is None)):
                         (k in self.outputs and self.outputs[k].value is None)):
                     msg = "Required parameter <%s> not set."
                     msg = "Required parameter <%s> not set."
                     raise ParameterError(msg % key)
                     raise ParameterError(msg % key)
-            self.run()
+            return self.run()
 
 
 
 
     def get_bash(self):
     def get_bash(self):
@@ -373,15 +378,18 @@ class Module(object):
         name = '_'.join(self.name.split('.')[1:])
         name = '_'.join(self.name.split('.')[1:])
         params = ', '.join([par.get_python() for par in self.params_list
         params = ', '.join([par.get_python() for par in self.params_list
                            if par.get_python() != ''])
                            if par.get_python() != ''])
+        flags = ''.join([flg.get_python()
+                         for flg in self.flags.values()
+                         if not flg.special and flg.get_python() != ''])
         special = ', '.join([flg.get_python()
         special = ', '.join([flg.get_python()
                              for flg in self.flags.values()
                              for flg in self.flags.values()
                              if flg.special and flg.get_python() != ''])
                              if flg.special and flg.get_python() != ''])
         #     pre name par flg special
         #     pre name par flg special
-        if self.flags and special:
+        if flags and special:
             return "%s.%s(%s, flags=%r, %s)" % (prefix, name, params,
             return "%s.%s(%s, flags=%r, %s)" % (prefix, name, params,
-                                                self.flags, special)
-        elif self.flags:
-            return "%s.%s(%s, flags=%r)" % (prefix, name, params, self.flags)
+                                                flags, special)
+        elif flags:
+            return "%s.%s(%s, flags=%r)" % (prefix, name, params, flags)
         elif special:
         elif special:
             return "%s.%s(%s, %s)" % (prefix, name, params, special)
             return "%s.%s(%s, %s)" % (prefix, name, params, special)
         else:
         else:
@@ -406,7 +414,7 @@ class Module(object):
              # transform each parameter in string
              # transform each parameter in string
              [str(param) for param in line if param is not None])
              [str(param) for param in line if param is not None])
              # make a list of parameters with only 3 param per line
              # make a list of parameters with only 3 param per line
-             for line in izip_longest(*[iter(self.params_list)] * 3)]),)
+             for line in zip_longest(*[iter(self.params_list)] * 3)]),)
         params = '\n'.join([par.__doc__ for par in self.params_list])
         params = '\n'.join([par.__doc__ for par in self.params_list])
         flags = self.flags.__doc__
         flags = self.flags.__doc__
         return '\n'.join([head, params, DOC['flag_head'], flags, DOC['foot']])
         return '\n'.join([head, params, DOC['flag_head'], flags, DOC['foot']])
@@ -472,6 +480,7 @@ class Module(object):
             self.outputs['stdout'].value = stdout if stdout else ''
             self.outputs['stdout'].value = stdout if stdout else ''
             self.outputs['stderr'].value = stderr if stderr else ''
             self.outputs['stderr'].value = stderr if stderr else ''
             self.time = time.time() - start
             self.time = time.time() - start
+        return self
 
 
 ###############################################################################
 ###############################################################################
 
 

+ 5 - 4
lib/python/pygrass/modules/interface/parameter.py

@@ -4,12 +4,12 @@ Created on Tue Apr  2 18:31:47 2013
 
 
 @author: pietro
 @author: pietro
 """
 """
-
-from __future__ import print_function
+from __future__ import (nested_scopes, generators, division, absolute_import,
+                        with_statement, print_function, unicode_literals)
 import re
 import re
 
 
 
 
-from read import GETTYPE, element2dict, DOC
+from .read import GETTYPE, element2dict, DOC
 
 
 
 
 class Parameter(object):
 class Parameter(object):
@@ -116,7 +116,8 @@ class Parameter(object):
                     raise ValueError(values_error % (self.name, self.values))
                     raise ValueError(values_error % (self.name, self.values))
             else:
             else:
                 self._value = value
                 self._value = value
-        elif self.type is str and isinstance(value, unicode):
+        # was: elif self.type is str and isinstance(value, unicode):
+        elif self.type is str and isinstance(value, str):
             if hasattr(self, 'values'):
             if hasattr(self, 'values'):
                 if value in self.values:
                 if value in self.values:
                     self._value = value
                     self._value = value

+ 2 - 1
lib/python/pygrass/modules/interface/read.py

@@ -4,7 +4,8 @@ Created on Tue Apr  2 18:30:34 2013
 
 
 @author: pietro
 @author: pietro
 """
 """
-from __future__ import print_function
+from __future__ import (nested_scopes, generators, division, absolute_import,
+                        with_statement, print_function, unicode_literals)
 
 
 
 
 def read_keydesc(par):
 def read_keydesc(par):

+ 3 - 1
lib/python/pygrass/modules/interface/typedict.py

@@ -4,6 +4,8 @@ Created on Tue Apr  2 18:37:02 2013
 
 
 @author: pietro
 @author: pietro
 """
 """
+from __future__ import (nested_scopes, generators, division, absolute_import,
+                        with_statement, print_function, unicode_literals)
 from copy import deepcopy
 from copy import deepcopy
 try:
 try:
     from collections import OrderedDict
     from collections import OrderedDict
@@ -48,7 +50,7 @@ class TypeDict(OrderedDict):
 
 
     def __deepcopy__(self, memo):
     def __deepcopy__(self, memo):
         obj = TypeDict(self._type)
         obj = TypeDict(self._type)
-        for k, v in self.iteritems():
+        for k, v in self.items():
             obj[k] = deepcopy(v)
             obj[k] = deepcopy(v)
         return obj
         return obj
 
 

+ 3 - 2
lib/python/pygrass/modules/shortcuts.py

@@ -4,12 +4,13 @@ Created on Tue Apr  2 18:49:11 2013
 
 
 @author: pietro
 @author: pietro
 """
 """
-from __future__ import print_function
+from __future__ import (nested_scopes, generators, division, absolute_import,
+                        with_statement, print_function, unicode_literals)
 import fnmatch
 import fnmatch
 
 
 
 
 from grass.script.core import get_commands
 from grass.script.core import get_commands
-from interface import Module
+from .interface import Module
 
 
 _CMDS = list(get_commands()[0])
 _CMDS = list(get_commands()[0])
 _CMDS.sort()
 _CMDS.sort()

+ 43 - 54
lib/python/pygrass/raster/__init__.py

@@ -4,6 +4,9 @@ Created on Fri May 25 12:56:33 2012
 
 
 @author: pietro
 @author: pietro
 """
 """
+from __future__ import (nested_scopes, generators, division, absolute_import,
+                        with_statement, print_function, unicode_literals)
+import os
 import ctypes
 import ctypes
 import numpy as np
 import numpy as np
 
 
@@ -27,11 +30,11 @@ from grass.pygrass import functions
 #
 #
 # import raster classes
 # import raster classes
 #
 #
-from abstract import RasterAbstractBase, Info
-from raster_type import TYPE as RTYPE, RTYPE_STR
-from buffer import Buffer
-from segment import Segment
-from rowio import RowIO
+from .abstract import RasterAbstractBase, Info
+from .raster_type import TYPE as RTYPE, RTYPE_STR
+from .buffer import Buffer
+from .segment import Segment
+from .rowio import RowIO
 
 
 
 
 class RasterRow(RasterAbstractBase):
 class RasterRow(RasterAbstractBase):
@@ -169,14 +172,20 @@ class RasterRow(RasterAbstractBase):
 
 
         # check if exist and instantiate all the private attributes
         # check if exist and instantiate all the private attributes
         if self.exist():
         if self.exist():
-            self.info = Info(self.name, self.mapset)
+            self.info.read()
+            self.cats.mtype = self.mtype
+            self.cats.read()
+            self.hist.read()
             if self.mode == 'r':
             if self.mode == 'r':
                 # the map exist, read mode
                 # the map exist, read mode
                 self._fd = libraster.Rast_open_old(self.name, self.mapset)
                 self._fd = libraster.Rast_open_old(self.name, self.mapset)
                 self._gtype = libraster.Rast_get_map_type(self._fd)
                 self._gtype = libraster.Rast_get_map_type(self._fd)
                 self.mtype = RTYPE_STR[self._gtype]
                 self.mtype = RTYPE_STR[self._gtype]
-                self.cats.read(self)
-                self.hist.read(self.name)
+#                try:
+#                    self.cats.read(self)
+#                    self.hist.read(self.name)
+#                except:
+#                    import ipdb; ipdb.set_trace()
             elif self.overwrite:
             elif self.overwrite:
                 if self._gtype is None:
                 if self._gtype is None:
                     raise OpenError(_("Raster type not defined"))
                     raise OpenError(_("Raster type not defined"))
@@ -269,7 +278,7 @@ class RasterSegment(RasterAbstractBase):
         if isinstance(key, slice):
         if isinstance(key, slice):
             #Get the start, stop, and step from the slice
             #Get the start, stop, and step from the slice
             return [self.put_row(ii, row)
             return [self.put_row(ii, row)
-                    for ii in xrange(*key.indices(len(self)))]
+                    for ii in range(*key.indices(len(self)))]
         elif isinstance(key, tuple):
         elif isinstance(key, tuple):
             x, y = key
             x, y = key
             return self.put(x, y, row)
             return self.put(x, y, row)
@@ -287,7 +296,7 @@ class RasterSegment(RasterAbstractBase):
         """Transform an existing map to segment file.
         """Transform an existing map to segment file.
         """
         """
         row_buffer = Buffer((self._cols), self.mtype)
         row_buffer = Buffer((self._cols), self.mtype)
-        for row in xrange(self._rows):
+        for row in range(self._rows):
             libraster.Rast_get_row(
             libraster.Rast_get_row(
                 self._fd, row_buffer.p, row, self._gtype)
                 self._fd, row_buffer.p, row, self._gtype)
             self.segment.put_row(row, row_buffer)
             self.segment.put_row(row, row_buffer)
@@ -297,7 +306,7 @@ class RasterSegment(RasterAbstractBase):
         """Transform the segment file to a map.
         """Transform the segment file to a map.
         """
         """
         row_buffer = Buffer((self._cols), self.mtype)
         row_buffer = Buffer((self._cols), self.mtype)
-        for row in xrange(self._rows):
+        for row in range(self._rows):
             row_buffer = self.segment.get_row(row, row_buffer)
             row_buffer = self.segment.get_row(row, row_buffer)
             libraster.Rast_put_row(self._fd, row_buffer.p, self._gtype)
             libraster.Rast_put_row(self._fd, row_buffer.p, self._gtype)
 
 
@@ -387,7 +396,10 @@ class RasterSegment(RasterAbstractBase):
         self.overwrite = overwrite if overwrite is not None else self.overwrite
         self.overwrite = overwrite if overwrite is not None else self.overwrite
 
 
         if self.exist():
         if self.exist():
-            self.info = Info(self.name, self.mapset)
+            self.info.read()
+            self.cats.mtype = self.mtype
+            self.cats.read()
+            self.hist.read()
             if ((self.mode == "w" or self.mode == "rw") and
             if ((self.mode == "w" or self.mode == "rw") and
                     self.overwrite is False):
                     self.overwrite is False):
                 str_err = _("Raster map <{0}> already exists. Use overwrite.")
                 str_err = _("Raster map <{0}> already exists. Use overwrite.")
@@ -579,51 +591,25 @@ class RasterNumpy(np.memmap, RasterAbstractBase):
         @return 0 on success
         @return 0 on success
         @return non-zero code on failure
         @return non-zero code on failure
         """
         """
-        self.null = None
+        with RasterRow(self.name, self.mapset, mode='r') as rst:
+            buff = rst[0]
+            for i in range(len(rst)):
+                self[i] = rst.get_row(i, buff)
 
 
-        size, kind = self._get_flags(self.dtype.itemsize, self.dtype.kind)
-        kind = 'f' if kind == 'd' else kind
-        ret = grasscore.run_command('r.out.bin', flags=kind,
-                                    input=self._name, output=self.filename,
-                                    bytes=size, null=self.null,
-                                    quiet=True)
-        return ret
 
 
     def _write(self):
     def _write(self):
         """
         """
         r.in.bin input=/home/pietro/docdat/phd/thesis/gis/north_carolina/user1/.tmp/eraclito/14325.0 output=new title='' bytes=1,anull='' --verbose --overwrite north=228500.0 south=215000.0 east=645000.0 west=630000.0 rows=1350 cols=1500
         r.in.bin input=/home/pietro/docdat/phd/thesis/gis/north_carolina/user1/.tmp/eraclito/14325.0 output=new title='' bytes=1,anull='' --verbose --overwrite north=228500.0 south=215000.0 east=645000.0 west=630000.0 rows=1350 cols=1500
 
 
         """
         """
-        self.tofile(self.filename)
-        size, kind = self._get_flags(self.dtype.itemsize, self.dtype.kind)
-        #print size, kind
-        if kind == 'i':
-            kind = None
-            size = 4
-        size = None if kind == 'f' else size
-
-        # To be set in the future
-        self.title = None
-        self.null = None
-
-        #import pdb; pdb.set_trace()
-        if self.mode in ('w+', 'r+'):
-            if not self._name:
-                import os
-                self._name = "doctest_%i" % os.getpid()
-            ret = grasscore.run_command('r.in.bin', flags=kind,
-                                        input=self.filename, output=self._name,
-                                        title=self.title, bytes=size,
-                                        anull=self.null,
-                                        overwrite=self.overwrite,
-                                        verbose=True,
-                                        north=self.reg.north,
-                                        south=self.reg.south,
-                                        east=self.reg.east,
-                                        west=self.reg.west,
-                                        rows=self.reg.rows,
-                                        cols=self.reg.cols)
-            return ret
+        if not self.exist() or self.mode != 'r':
+            self.flush()
+            buff = Buffer(self[0].shape, mtype=self.mtype)
+            with RasterRow(self.name, self.mapset, mode='w',
+                           mtype=self.mtype) as rst:
+                for i in range(len(rst)):
+                    buff[:] = self[i][:]
+                    rst.put_row(buff[:])
 
 
     def open(self, mtype='', null=None, overwrite=None):
     def open(self, mtype='', null=None, overwrite=None):
         """Open the map, if the map already exist: determine the map type
         """Open the map, if the map already exist: determine the map type
@@ -641,6 +627,10 @@ class RasterNumpy(np.memmap, RasterAbstractBase):
         self.null = null
         self.null = null
         # rows and cols already set in __new__
         # rows and cols already set in __new__
         if self.exist():
         if self.exist():
+            self.info.read()
+            self.cats.mtype = self.mtype
+            self.cats.read()
+            self.hist.read()
             self._read()
             self._read()
         else:
         else:
             if mtype:
             if mtype:
@@ -652,8 +642,7 @@ class RasterNumpy(np.memmap, RasterAbstractBase):
 
 
     def close(self):
     def close(self):
         self._write()
         self._write()
-        np.memmap._close(self)
-        grasscore.try_remove(self.filename)
+        os.remove(self.filename)
         self._fd = None
         self._fd = None
 
 
     def get_value(self, point, region=None):
     def get_value(self, point, region=None):
@@ -676,7 +665,7 @@ def random_map_only_columns(mapname, mtype, overwrite=True, factor=100):
     row_buf = Buffer((region.cols, ), mtype,
     row_buf = Buffer((region.cols, ), mtype,
                      buffer=(np.random.random(region.cols,) * factor).data)
                      buffer=(np.random.random(region.cols,) * factor).data)
     random_map.open('w', mtype, overwrite)
     random_map.open('w', mtype, overwrite)
-    for _ in xrange(region.rows):
+    for _ in range(region.rows):
         random_map.put_row(row_buf)
         random_map.put_row(row_buf)
     random_map.close()
     random_map.close()
     return random_map
     return random_map
@@ -686,7 +675,7 @@ def random_map(mapname, mtype, overwrite=True, factor=100):
     region = Region()
     region = Region()
     random_map = RasterRow(mapname)
     random_map = RasterRow(mapname)
     random_map.open('w', mtype, overwrite)
     random_map.open('w', mtype, overwrite)
-    for _ in xrange(region.rows):
+    for _ in range(region.rows):
         row_buf = Buffer((region.cols, ), mtype,
         row_buf = Buffer((region.cols, ), mtype,
                          buffer=(np.random.random(region.cols,) * factor).data)
                          buffer=(np.random.random(region.cols,) * factor).data)
         random_map.put_row(row_buf)
         random_map.put_row(row_buf)

+ 19 - 13
lib/python/pygrass/raster/abstract.py

@@ -4,6 +4,8 @@ Created on Fri Aug 17 16:05:25 2012
 
 
 @author: pietro
 @author: pietro
 """
 """
+from __future__ import (nested_scopes, generators, division, absolute_import,
+                        with_statement, print_function, unicode_literals)
 import ctypes
 import ctypes
 
 
 #
 #
@@ -25,9 +27,9 @@ from grass.pygrass.shell.show import raw_figure
 #
 #
 # import raster classes
 # import raster classes
 #
 #
-from raster_type import TYPE as RTYPE
-from category import Category
-from history import History
+from .raster_type import TYPE as RTYPE
+from .category import Category
+from .history import History
 
 
 
 
 ## Define global variables to not exceed the 80 columns
 ## Define global variables to not exceed the 80 columns
@@ -62,14 +64,19 @@ class Info(object):
         self.name = name
         self.name = name
         self.mapset = mapset
         self.mapset = mapset
         self.c_region = ctypes.pointer(libgis.Cell_head())
         self.c_region = ctypes.pointer(libgis.Cell_head())
-        libraster.Rast_get_cellhd(name, mapset,
-                                  self.c_region)
-        self._get_range()
+        self.c_range = ctypes.pointer(libraster.Range())
 
 
     def _get_range(self):
     def _get_range(self):
-        self.c_range = ctypes.pointer(libraster.Range())
         libraster.Rast_read_range(self.name, self.mapset, self.c_range)
         libraster.Rast_read_range(self.name, self.mapset, self.c_range)
 
 
+    def _get_raster_region(self):
+        if self.name and self.mapset:
+            libraster.Rast_get_cellhd(self.name, self.mapset, self.c_region)
+
+    def read(self):
+        self._get_range()
+        self._get_raster_region()
+
     @property
     @property
     def north(self):
     def north(self):
         return self.c_region.contents.north
         return self.c_region.contents.north
@@ -196,10 +203,9 @@ class RasterAbstractBase(object):
         # when you open the file, using Rast_window_cols()
         # when you open the file, using Rast_window_cols()
         self._cols = None
         self._cols = None
         #self.region = Region()
         #self.region = Region()
-        self.cats = Category()
-        self.hist = History()
-        if self.exist():
-            self.info = Info(self.name, self.mapset)
+        self.hist = History(self.name, self.mapset)
+        self.cats = Category(self.name, self.mapset)
+        self.info = Info(self.name, self.mapset)
         self.mode = mode
         self.mode = mode
         self.mtype = mtype
         self.mtype = mtype
         self.overwrite = overwrite
         self.overwrite = overwrite
@@ -288,7 +294,7 @@ class RasterAbstractBase(object):
         if isinstance(key, slice):
         if isinstance(key, slice):
             #import pdb; pdb.set_trace()
             #import pdb; pdb.set_trace()
             #Get the start, stop, and step from the slice
             #Get the start, stop, and step from the slice
-            return (self.get_row(ii) for ii in xrange(*key.indices(len(self))))
+            return (self.get_row(ii) for ii in range(*key.indices(len(self))))
         elif isinstance(key, tuple):
         elif isinstance(key, tuple):
             x, y = key
             x, y = key
             return self.get(x, y)
             return self.get(x, y)
@@ -304,7 +310,7 @@ class RasterAbstractBase(object):
 
 
     def __iter__(self):
     def __iter__(self):
         """Return a constructor of the class"""
         """Return a constructor of the class"""
-        return (self.__getitem__(irow) for irow in xrange(self._rows))
+        return (self.__getitem__(irow) for irow in range(self._rows))
 
 
     def _repr_png_(self):
     def _repr_png_(self):
         return raw_figure(functions.r_export(self))
         return raw_figure(functions.r_export(self))

+ 1 - 1
lib/python/pygrass/raster/buffer.py

@@ -4,7 +4,7 @@ Created on Fri Jun  8 18:46:34 2012
 
 
 @author: pietro
 @author: pietro
 """
 """
-from raster_type import TYPE as RTYPE
+from .raster_type import TYPE as RTYPE
 import ctypes
 import ctypes
 import numpy as np
 import numpy as np
 
 

+ 23 - 35
lib/python/pygrass/raster/category.py

@@ -11,7 +11,7 @@ import grass.lib.raster as libraster
 
 
 from grass.pygrass.errors import GrassError
 from grass.pygrass.errors import GrassError
 
 
-from raster_type import TYPE as RTYPE
+from .raster_type import TYPE as RTYPE
 
 
 
 
 class Category(list):
 class Category(list):
@@ -65,9 +65,11 @@ class Category(list):
     >>> libraster.Rast_get_ith_c_cat(ctypes.byref(cats.cats), 0,
     >>> libraster.Rast_get_ith_c_cat(ctypes.byref(cats.cats), 0,
     ...                              min_cat, max_cat)
     ...                              min_cat, max_cat)
     """
     """
-    def __init__(self, mtype=None, *args, **kargs):
-        self._cats = libraster.Categories()
-        libraster.Rast_init_cats("", ctypes.byref(self._cats))
+    def __init__(self, name, mapset='', mtype=None, *args, **kargs):
+        self.name = name
+        self.mapset = mapset
+        self.c_cats = libraster.Categories()
+        libraster.Rast_init_cats("", ctypes.byref(self.c_cats))
         self._mtype = mtype
         self._mtype = mtype
         self._gtype = None if mtype is None else RTYPE[mtype]['grass type']
         self._gtype = None if mtype is None else RTYPE[mtype]['grass type']
         super(Category, self).__init__(*args, **kargs)
         super(Category, self).__init__(*args, **kargs)
@@ -85,11 +87,11 @@ class Category(list):
     mtype = property(fget=_get_mtype, fset=_set_mtype)
     mtype = property(fget=_get_mtype, fset=_set_mtype)
 
 
     def _get_title(self):
     def _get_title(self):
-        return libraster.Rast_get_cats_title(ctypes.byref(self._cats))
+        return libraster.Rast_get_cats_title(ctypes.byref(self.c_cats))
 
 
     def _set_title(self, newtitle):
     def _set_title(self, newtitle):
         return libraster.Rast_set_cats_title(newtitle,
         return libraster.Rast_set_cats_title(newtitle,
-                                             ctypes.byref(self._cats))
+                                             ctypes.byref(self.c_cats))
 
 
     title = property(fget=_get_title, fset=_set_title)
     title = property(fget=_get_title, fset=_set_title)
 
 
@@ -156,7 +158,7 @@ class Category(list):
         """
         """
         min_cat = ctypes.pointer(RTYPE[self.mtype]['grass def']())
         min_cat = ctypes.pointer(RTYPE[self.mtype]['grass def']())
         max_cat = ctypes.pointer(RTYPE[self.mtype]['grass def']())
         max_cat = ctypes.pointer(RTYPE[self.mtype]['grass def']())
-        lab = libraster.Rast_get_ith_cat(ctypes.byref(self._cats),
+        lab = libraster.Rast_get_ith_cat(ctypes.byref(self.c_cats),
                                          index,
                                          index,
                                          ctypes.cast(min_cat, ctypes.c_void_p),
                                          ctypes.cast(min_cat, ctypes.c_void_p),
                                          ctypes.cast(max_cat, ctypes.c_void_p),
                                          ctypes.cast(max_cat, ctypes.c_void_p),
@@ -186,7 +188,7 @@ class Category(list):
         err = libraster.Rast_set_cat(ctypes.cast(min_cat, ctypes.c_void_p),
         err = libraster.Rast_set_cat(ctypes.cast(min_cat, ctypes.c_void_p),
                                      ctypes.cast(max_cat, ctypes.c_void_p),
                                      ctypes.cast(max_cat, ctypes.c_void_p),
                                      label,
                                      label,
-                                     ctypes.byref(self._cats), self._gtype)
+                                     ctypes.byref(self.c_cats), self._gtype)
         # Manage C function Errors
         # Manage C function Errors
         if err == 1:
         if err == 1:
             return None
             return None
@@ -196,7 +198,7 @@ class Category(list):
             raise GrassError(_("Error executing: Rast_set_cat"))
             raise GrassError(_("Error executing: Rast_set_cat"))
 
 
     def __del__(self):
     def __del__(self):
-        libraster.Rast_free_cats(ctypes.byref(self._cats))
+        libraster.Rast_free_cats(ctypes.byref(self.c_cats))
 
 
     def get_cat(self, index):
     def get_cat(self, index):
         return self.__getitem__(index)
         return self.__getitem__(index)
@@ -210,19 +212,19 @@ class Category(list):
             raise TypeError("Index outside range.")
             raise TypeError("Index outside range.")
 
 
     def reset(self):
     def reset(self):
-        for i in xrange(len(self) - 1, -1, -1):
+        for i in range(len(self) - 1, -1, -1):
             del(self[i])
             del(self[i])
-        libraster.Rast_init_cats("", ctypes.byref(self._cats))
+        libraster.Rast_init_cats("", ctypes.byref(self.c_cats))
 
 
     def _read_cats(self):
     def _read_cats(self):
         """Copy from the C struct to the list"""
         """Copy from the C struct to the list"""
-        for i in xrange(self._cats.ncats):
+        for i in range(self.c_cats.ncats):
             self.append(self._get_c_cat(i))
             self.append(self._get_c_cat(i))
 
 
     def _write_cats(self):
     def _write_cats(self):
         """Copy from the list data to the C struct"""
         """Copy from the list data to the C struct"""
         # reset only the C struct
         # reset only the C struct
-        libraster.Rast_init_cats("", ctypes.byref(self._cats))
+        libraster.Rast_init_cats("", ctypes.byref(self.c_cats))
         # write to the c struct
         # write to the c struct
         for cat in self.__iter__():
         for cat in self.__iter__():
             label, min_cat, max_cat = cat
             label, min_cat, max_cat = cat
@@ -230,7 +232,7 @@ class Category(list):
                 max_cat = min_cat
                 max_cat = min_cat
             self._set_c_cat(label, min_cat, max_cat)
             self._set_c_cat(label, min_cat, max_cat)
 
 
-    def read(self, rast, mapset=None, mtype=None):
+    def read(self):
         """Read categories from a raster map
         """Read categories from a raster map
 
 
         The category file for raster map name in mapset is read into the
         The category file for raster map name in mapset is read into the
@@ -242,25 +244,15 @@ class Category(list):
                            struct Categories * 	pcats
                            struct Categories * 	pcats
                            )
                            )
         """
         """
-        if type(rast) == str:
-            mapname = rast
-            if mapset is None or mtype is None:
-                raise TypeError(_('Mapset and maptype must be specify'))
-        else:
-            mapname = rast.name
-            mapset = rast.mapset
-            mtype = rast.mtype
-
-        self.mtype = mtype
         self.reset()
         self.reset()
-        err = libraster.Rast_read_cats(mapname, mapset,
-                                       ctypes.byref(self._cats))
+        err = libraster.Rast_read_cats(self.name, self.mapset,
+                                       ctypes.byref(self.c_cats))
         if err == -1:
         if err == -1:
             raise GrassError("Can not read the categories.")
             raise GrassError("Can not read the categories.")
         # copy from C struct to list
         # copy from C struct to list
         self._read_cats()
         self._read_cats()
 
 
-    def write(self, map):
+    def write(self):
         """Writes the category file for the raster map name in the current
         """Writes the category file for the raster map name in the current
            mapset from the cats structure.
            mapset from the cats structure.
 
 
@@ -268,18 +260,14 @@ class Category(list):
                              struct Categories * 	cats
                              struct Categories * 	cats
                              )
                              )
         """
         """
-        if type(map) == str:
-            mapname = map
-        else:
-            mapname = map.name
         # copy from list to C struct
         # copy from list to C struct
         self._write_cats()
         self._write_cats()
         # write to the map
         # write to the map
-        libraster.Rast_write_cats(mapname, ctypes.byref(self._cats))
+        libraster.Rast_write_cats(self.name, ctypes.byref(self.c_cats))
 
 
     def copy(self, category):
     def copy(self, category):
         """Copy from another Category class"""
         """Copy from another Category class"""
-        libraster.Rast_copy_cats(ctypes.byref(self._cats),     # to
+        libraster.Rast_copy_cats(ctypes.byref(self.c_cats),     # to
                                  ctypes.byref(category._cats))  # from
                                  ctypes.byref(category._cats))  # from
         self._read_cats()
         self._read_cats()
 
 
@@ -342,7 +330,7 @@ class Category(list):
             f.write('\n'.join(cats))
             f.write('\n'.join(cats))
 
 
     def sort(self):
     def sort(self):
-        libraster.Rast_sort_cats(ctypes.byref(self._cats))
+        libraster.Rast_sort_cats(ctypes.byref(self.c_cats))
 
 
     def labels(self):
     def labels(self):
-        return map(itemgetter(0), self)
+        return list(map(itemgetter(0), self))

+ 32 - 17
lib/python/pygrass/raster/history.py

@@ -36,12 +36,27 @@ class History(object):
 
 
     ..
     ..
     """
     """
-    def __init__(self, name=''):
+    def __init__(self, name, mapset='', mtype='',
+                 creator='', src1='', src2='', keyword='',
+                 date='', title=''):
         self.c_hist = ctypes.pointer(libraster.History())
         self.c_hist = ctypes.pointer(libraster.History())
         #                'Tue Nov  7 01:11:23 2006'
         #                'Tue Nov  7 01:11:23 2006'
         self.date_fmt = '%a %b  %d %H:%M:%S %Y'
         self.date_fmt = '%a %b  %d %H:%M:%S %Y'
-        if name:
-            self.read(name)
+        self.name = name
+        self.mapset = mapset
+        self.mtype = mtype
+        self.creator = creator
+        self.src1 = src1
+        self.src2 = src2
+        self.keyword = keyword
+        self.date = date
+        self.title = title
+
+    def __repr__(self):
+        attrs = ['name', 'mapset', 'mtype', 'creator', 'src1', 'src2',
+                 'keyword', 'date', 'title']
+        return "History(%s)" % ', '.join(["%s=%r" % (attr, getattr(self, attr))
+                                          for attr in attrs])
 
 
     def __del__(self):
     def __del__(self):
         """Rast_free_history"""
         """Rast_free_history"""
@@ -104,13 +119,15 @@ class History(object):
     def _get_date(self):
     def _get_date(self):
         date_str = libraster.Rast_get_history(self.c_hist,
         date_str = libraster.Rast_get_history(self.c_hist,
                                               libraster.HIST_MAPID)
                                               libraster.HIST_MAPID)
-        return datetime.datetime.strptime(date_str, self.date_fmt)
+        if date_str:
+            return datetime.datetime.strptime(date_str, self.date_fmt)
 
 
     def _set_date(self, datetimeobj):
     def _set_date(self, datetimeobj):
-        date_str = datetimeobj.strftime(self.date_fmt)
-        return libraster.Rast_set_history(self.c_hist,
-                                          libraster.HIST_MAPID,
-                                          ctypes.c_char_p(date_str))
+        if datetimeobj:
+            date_str = datetimeobj.strftime(self.date_fmt)
+            return libraster.Rast_set_history(self.c_hist,
+                                              libraster.HIST_MAPID,
+                                              ctypes.c_char_p(date_str))
 
 
     date = property(fget=_get_date, fset=_set_date)
     date = property(fget=_get_date, fset=_set_date)
 
 
@@ -203,7 +220,7 @@ class History(object):
         libraster.Rast_history_line(self.c_hist,
         libraster.Rast_history_line(self.c_hist,
                                     ctypes.c_int(line))
                                     ctypes.c_int(line))
 
 
-    def read(self, name):
+    def read(self):
         """Rast_read_history. ::
         """Rast_read_history. ::
 
 
             >>> import grass.lib.gis as libgis
             >>> import grass.lib.gis as libgis
@@ -221,17 +238,15 @@ class History(object):
 
 
         ..
         ..
         """
         """
-        libraster.Rast_read_history(ctypes.c_char_p(name),
-                                    ctypes.c_char_p(''),
-                                    self.c_hist)
+        libraster.Rast_read_history(self.name, self.mapset, self.c_hist)
 
 
-    def write(self, name):
+    def write(self):
         """Rast_write_history"""
         """Rast_write_history"""
-        libraster.Rast_write_history(ctypes.c_char_p(name),
+        libraster.Rast_write_history(self.name,
                                      self.c_hist)
                                      self.c_hist)
 
 
-    def short(self, name, maptype,):
+    def short(self):
         """Rast_short_history"""
         """Rast_short_history"""
-        libraster.Rast_short_history(ctypes.c_char_p(name),
-                                     ctypes.c_char_p(maptype),
+        libraster.Rast_short_history(self.name,
+                                     'raster',
                                      self.c_hist)
                                      self.c_hist)

+ 1 - 1
lib/python/pygrass/raster/rowio.py

@@ -10,7 +10,7 @@ import grass.lib.rowio as librowio
 import grass.lib.raster as librast
 import grass.lib.raster as librast
 
 
 from grass.pygrass.errors import GrassError
 from grass.pygrass.errors import GrassError
-from raster_type import TYPE as RTYPE
+from .raster_type import TYPE as RTYPE
 
 
 
 
 CMPFUNC = ctypes.CFUNCTYPE(ctypes.c_int,
 CMPFUNC = ctypes.CFUNCTYPE(ctypes.c_int,

+ 1 - 1
lib/python/pygrass/raster/segment.py

@@ -8,7 +8,7 @@ import ctypes
 import grass.lib.gis as libgis
 import grass.lib.gis as libgis
 import grass.lib.raster as libraster
 import grass.lib.raster as libraster
 import grass.lib.segment as libseg
 import grass.lib.segment as libseg
-from raster_type import TYPE as RTYPE
+from .raster_type import TYPE as RTYPE
 
 
 
 
 class Segment(object):
 class Segment(object):

+ 2 - 2
lib/python/pygrass/shell/__init__.py

@@ -5,6 +5,6 @@ Created on Sun Jun 23 15:06:46 2013
 @author: pietro
 @author: pietro
 """
 """
 
 
-import conversion
-import show
+from . import conversion
+from . import show
 
 

+ 38 - 35
lib/python/pygrass/tests/benchmark.py

@@ -4,6 +4,9 @@ Created on Sat Jun 16 20:24:56 2012
 
 
 @author: soeren
 @author: soeren
 """
 """
+from __future__ import (nested_scopes, generators, division, absolute_import,
+                        with_statement, print_function, unicode_literals)
+
 import optparse
 import optparse
 #import numpy as np
 #import numpy as np
 import time
 import time
@@ -28,8 +31,8 @@ def test__RasterNumpy_value_access__if():
     test_c = pygrass.RasterNumpy(name="test_c", mtype="CELL", mode="w+", overwrite=True)
     test_c = pygrass.RasterNumpy(name="test_c", mtype="CELL", mode="w+", overwrite=True)
     test_c.open()
     test_c.open()
 
 
-    for row in xrange(test_a.rows):
-        for col in xrange(test_a.cols):
+    for row in range(test_a.rows):
+        for col in range(test_a.cols):
             test_c[row, col] = test_a[row, col] > 50
             test_c[row, col] = test_a[row, col] > 50
 
 
     test_a.close()
     test_a.close()
@@ -45,8 +48,8 @@ def test__RasterNumpy_value_access__add():
     test_c = pygrass.RasterNumpy(name="test_c", mtype="DCELL", mode="w+", overwrite=True)
     test_c = pygrass.RasterNumpy(name="test_c", mtype="DCELL", mode="w+", overwrite=True)
     test_c.open()
     test_c.open()
 
 
-    for row in xrange(test_a.rows):
-        for col in xrange(test_a.cols):
+    for row in range(test_a.rows):
+        for col in range(test_a.cols):
             test_c[row, col] = test_a[row, col] + test_b[row, col]
             test_c[row, col] = test_a[row, col] + test_b[row, col]
 
 
     test_a.close()
     test_a.close()
@@ -60,7 +63,7 @@ def test__RasterNumpy_row_access__if():
     test_c = pygrass.RasterNumpy(name="test_c", mtype="CELL", mode="w+", overwrite=True)
     test_c = pygrass.RasterNumpy(name="test_c", mtype="CELL", mode="w+", overwrite=True)
     test_c.open()
     test_c.open()
 
 
-    for row in xrange(test_a.rows):
+    for row in range(test_a.rows):
         test_c[row] = test_a[row] > 50
         test_c[row] = test_a[row] > 50
 
 
     test_a.close()
     test_a.close()
@@ -76,7 +79,7 @@ def test__RasterNumpy_row_access__add():
     test_c = pygrass.RasterNumpy(name="test_c", mtype="DCELL", mode="w+", overwrite=True)
     test_c = pygrass.RasterNumpy(name="test_c", mtype="DCELL", mode="w+", overwrite=True)
     test_c.open()
     test_c.open()
 
 
-    for row in xrange(test_a.rows):
+    for row in range(test_a.rows):
         test_c[row] = test_a[row] + test_b[row]
         test_c[row] = test_a[row] + test_b[row]
 
 
     test_a.close()
     test_a.close()
@@ -120,9 +123,9 @@ def test__RasterSegment_value_access__if():
 
 
     buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
     buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
 
 
-    for row in xrange(test_a.rows):
+    for row in range(test_a.rows):
         test_a.get_row(row, buff_a)
         test_a.get_row(row, buff_a)
-        for col in xrange(test_a.cols):
+        for col in range(test_a.cols):
             test_c.put(row, col, buff_a[col] > 50)
             test_c.put(row, col, buff_a[col] > 50)
 
 
     test_a.close()
     test_a.close()
@@ -141,10 +144,10 @@ def test__RasterSegment_value_access__add():
     buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
     buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
     buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)
     buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)
 
 
-    for row in xrange(test_a.rows):
+    for row in range(test_a.rows):
         test_a.get_row(row, buff_a)
         test_a.get_row(row, buff_a)
         test_b.get_row(row,buff_b)
         test_b.get_row(row,buff_b)
-        for col in xrange(test_a.cols):
+        for col in range(test_a.cols):
             test_c.put(row, col, buff_a[col] + buff_b[col])
             test_c.put(row, col, buff_a[col] + buff_b[col])
 
 
     test_a.close()
     test_a.close()
@@ -160,7 +163,7 @@ def test__RasterSegment_row_access__if():
 
 
     buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
     buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
 
 
-    for row in xrange(test_a.rows):
+    for row in range(test_a.rows):
         test_a.get_row(row, buff_a)
         test_a.get_row(row, buff_a)
         test_c.put_row(row, buff_a > 50)
         test_c.put_row(row, buff_a > 50)
 
 
@@ -180,7 +183,7 @@ def test__RasterSegment_row_access__add():
     buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
     buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
     buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)
     buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)
 
 
-    for row in xrange(test_a.rows):
+    for row in range(test_a.rows):
         test_a.get_row(row, buff_a)
         test_a.get_row(row, buff_a)
         test_b.get_row(row,buff_b)
         test_b.get_row(row,buff_b)
         test_c.put_row(row, buff_a + buff_b)
         test_c.put_row(row, buff_a + buff_b)
@@ -203,11 +206,11 @@ def test__RasterRow_value_access__add():
     buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)
     buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)
     buff_c = pygrass.Buffer(test_b.cols, test_b.mtype)
     buff_c = pygrass.Buffer(test_b.cols, test_b.mtype)
 
 
-    for row in xrange(test_a.rows):
+    for row in range(test_a.rows):
         test_a.get_row(row, buff_a)
         test_a.get_row(row, buff_a)
         test_b.get_row(row,buff_b)
         test_b.get_row(row,buff_b)
 
 
-        for col in xrange(test_a.cols):
+        for col in range(test_a.cols):
             buff_c[col] = buff_a[col] + buff_b[col]
             buff_c[col] = buff_a[col] + buff_b[col]
 
 
         test_c.put_row(buff_c)
         test_c.put_row(buff_c)
@@ -226,10 +229,10 @@ def test__RasterRow_value_access__if():
     buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
     buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
     buff_c = pygrass.Buffer(test_a.cols, test_a.mtype)
     buff_c = pygrass.Buffer(test_a.cols, test_a.mtype)
 
 
-    for row in xrange(test_a.rows):
+    for row in range(test_a.rows):
         test_a.get_row(row, buff_a)
         test_a.get_row(row, buff_a)
 
 
-        for col in xrange(test_a.cols):
+        for col in range(test_a.cols):
             buff_c[col] = buff_a[col] > 50
             buff_c[col] = buff_a[col] > 50
 
 
         test_c.put_row(buff_c)
         test_c.put_row(buff_c)
@@ -250,7 +253,7 @@ def test__RasterRowIO_row_access__add():
     buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
     buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
     buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)
     buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)
 
 
-    for row in xrange(test_a.rows):
+    for row in range(test_a.rows):
         test_a.get_row(row, buff_a)
         test_a.get_row(row, buff_a)
         test_b.get_row(row,buff_b)
         test_b.get_row(row,buff_b)
         test_c.put_row(buff_a + buff_b)
         test_c.put_row(buff_a + buff_b)
@@ -268,7 +271,7 @@ def test__RasterRowIO_row_access__if():
 
 
     buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
     buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
 
 
-    for row in xrange(test_a.rows):
+    for row in range(test_a.rows):
         test_a.get_row(row, buff_a)
         test_a.get_row(row, buff_a)
         test_c.put_row(buff_a > 50)
         test_c.put_row(buff_a > 50)
 
 
@@ -288,7 +291,7 @@ def test__RasterRow_row_access__add():
     buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
     buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
     buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)
     buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)
 
 
-    for row in xrange(test_a.rows):
+    for row in range(test_a.rows):
         test_a.get_row(row, buff_a)
         test_a.get_row(row, buff_a)
         test_b.get_row(row,buff_b)
         test_b.get_row(row,buff_b)
         test_c.put_row(buff_a + buff_b)
         test_c.put_row(buff_a + buff_b)
@@ -306,7 +309,7 @@ def test__RasterRow_row_access__if():
 
 
     buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
     buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
 
 
-    for row in xrange(test_a.rows):
+    for row in range(test_a.rows):
         test_a.get_row(row, buff_a)
         test_a.get_row(row, buff_a)
         test_c.put_row(buff_a > 50)
         test_c.put_row(buff_a > 50)
 
 
@@ -322,7 +325,7 @@ def test__mapcalc__if():
 def mytimer(func, runs=1):
 def mytimer(func, runs=1):
     times = []
     times = []
     t = 0.0
     t = 0.0
-    for _ in xrange(runs):
+    for _ in range(runs):
         start = time.time()
         start = time.time()
         func()
         func()
         end = time.time()
         end = time.time()
@@ -363,15 +366,15 @@ def run_benchmark(resolution_list, runs, testdict, profile):
         result['rows'] = region.rows
         result['rows'] = region.rows
         result['cells'] = region.rows * region.cols
         result['cells'] = region.rows * region.cols
         result['results'] = copy.deepcopy(testdict)
         result['results'] = copy.deepcopy(testdict)
-        for execmode, operation in result['results'].iteritems():
+        for execmode, operation in result['results'].items():
             print(execmode)
             print(execmode)
-            for oper, operdict in operation.iteritems():
+            for oper, operdict in operation.items():
                 operdict['time'], operdict['times'] = mytimer(operdict['func'],runs)
                 operdict['time'], operdict['times'] = mytimer(operdict['func'],runs)
                 if profile:
                 if profile:
                     filename = '{}_{}_{}'.format(execmode, oper, profile)
                     filename = '{}_{}_{}'.format(execmode, oper, profile)
                     cProfile.runctx(operdict['func'].__name__ + '()',
                     cProfile.runctx(operdict['func'].__name__ + '()',
                                     globals(), locals(), filename = filename)
                                     globals(), locals(), filename = filename)
-                print('    {0}: {1: 40.6f}s'.format(oper, operdict['time']))
+                print(('    {0}: {1: 40.6f}s'.format(oper, operdict['time'])))
                 del(operdict['func'])
                 del(operdict['func'])
 
 
         regions.append(result)
         regions.append(result)
@@ -380,7 +383,7 @@ def run_benchmark(resolution_list, runs, testdict, profile):
     return regions
     return regions
 
 
 def get_testlist(loc):
 def get_testlist(loc):
-    testlist = [test for test in loc.keys() if 'test' in test[:5]]
+    testlist = [test for test in list(loc.keys()) if 'test' in test[:5]]
     testlist.sort()
     testlist.sort()
     return testlist
     return testlist
 
 
@@ -389,7 +392,7 @@ def get_testdict(testlist):
     for testfunc in testlist:
     for testfunc in testlist:
         #import pdb; pdb.set_trace()
         #import pdb; pdb.set_trace()
         dummy, execmode, operation = testfunc.split('__')
         dummy, execmode, operation = testfunc.split('__')
-        if execmode in testdict.keys():
+        if execmode in list(testdict.keys()):
             testdict[execmode][operation] = collections.OrderedDict()
             testdict[execmode][operation] = collections.OrderedDict()
             testdict[execmode][operation]['func'] = loc[testfunc]
             testdict[execmode][operation]['func'] = loc[testfunc]
         else:
         else:
@@ -399,14 +402,14 @@ def get_testdict(testlist):
     return testdict
     return testdict
 
 
 def print_test(testdict):
 def print_test(testdict):
-    for execmode, operation in testdict.iteritems():
-        print execmode
-        for oper, operdict in operation.iteritems():
-            print '    ', oper
-            for key, value in operdict.iteritems():
-                print '        ', key
-
-TXT = u"""
+    for execmode, operation in testdict.items():
+        print(execmode)
+        for oper, operdict in operation.items():
+            print('    ', oper)
+            for key, value in operdict.items():
+                print('        ', key)
+
+TXT = """
 {% for region in regions %}
 {% for region in regions %}
 {{ '#'*60 }}
 {{ '#'*60 }}
 ### Benchmark cols = {{ region.cols }} rows = {{ region.rows}} cells = {{ region.cells }}
 ### Benchmark cols = {{ region.cols }} rows = {{ region.rows}} cells = {{ region.cells }}
@@ -506,7 +509,7 @@ def main(testdict):
         pickle.dump(results, output)
         pickle.dump(results, output)
         output.close()
         output.close()
     #import pdb; pdb.set_trace()
     #import pdb; pdb.set_trace()
-    print get_txt(results)
+    print(get_txt(results))
 
 
 
 
 #add options
 #add options

+ 11 - 8
lib/python/pygrass/tests/set_mapset.py

@@ -5,6 +5,9 @@ Created on Thu Aug 23 11:07:38 2012
 @author: pietro
 @author: pietro
 
 
 """
 """
+from __future__ import (nested_scopes, generators, division, absolute_import,
+                        with_statement, print_function, unicode_literals)
+
 import os
 import os
 import subprocess
 import subprocess
 import optparse
 import optparse
@@ -31,8 +34,8 @@ def main():
     parser.add_option("-P", "--password", dest="passwd", default=None,
     parser.add_option("-P", "--password", dest="passwd", default=None,
                       help="PostgreSQL password for user [default=%default]")
                       help="PostgreSQL password for user [default=%default]")
     parser.add_option("-D", "--database", dest="db", default='pygrassdb_doctest',
     parser.add_option("-D", "--database", dest="db", default='pygrassdb_doctest',
-                      help="PostgreSQL database name [default=%default]")                      
-                      
+                      help="PostgreSQL database name [default=%default]")
+
     (opts, args) = parser.parse_args()
     (opts, args) = parser.parse_args()
     #
     #
     # Create DB
     # Create DB
@@ -41,19 +44,19 @@ def main():
     createdb = ['createdb', '--encoding=UTF-8', '--owner=%s' % opts.user,
     createdb = ['createdb', '--encoding=UTF-8', '--owner=%s' % opts.user,
                 '--host=localhost', '--username=%s' % opts.user, opts.db]
                 '--host=localhost', '--username=%s' % opts.user, opts.db]
     if opts.passwd:
     if opts.passwd:
-        print opts.passwd
+        print(opts.passwd)
         createdb.append("--password=%s" % opts.passwd)
         createdb.append("--password=%s" % opts.passwd)
     else:
     else:
         createdb.append("--no-password")
         createdb.append("--no-password")
     subprocess.Popen(createdb)
     subprocess.Popen(createdb)
-    
+
     #
     #
     # set postgreSQL
     # set postgreSQL
     #
     #
     print("\n\nSet Postgres connection...\n")
     print("\n\nSet Postgres connection...\n")
     grasscore.run_command('db.connect', driver='pg',
     grasscore.run_command('db.connect', driver='pg',
                           database='host=localhost,dbname=%s' % opts.db)
                           database='host=localhost,dbname=%s' % opts.db)
-    
+
     grasscore.run_command('db.login', user=opts.user)
     grasscore.run_command('db.login', user=opts.user)
     print("\n\nCopy the map from PERMANENT to user1...\n")
     print("\n\nCopy the map from PERMANENT to user1...\n")
     grasscore.run_command('g.copy',
     grasscore.run_command('g.copy',
@@ -61,8 +64,8 @@ def main():
                           overwrite=True)
                           overwrite=True)
     print("\n\nBuild topology...\n")
     print("\n\nBuild topology...\n")
     grasscore.run_command('v.build', map='boundary_municp_pg', overwrite=True)
     grasscore.run_command('v.build', map='boundary_municp_pg', overwrite=True)
-    
-    
+
+
     #
     #
     # set sqlite
     # set sqlite
     #
     #
@@ -76,6 +79,6 @@ def main():
                           overwrite=True)
                           overwrite=True)
     print("\n\nBuild topology...\n")
     print("\n\nBuild topology...\n")
     grasscore.run_command('v.build', map='boundary_municp_sqlite', overwrite=True)
     grasscore.run_command('v.build', map='boundary_municp_sqlite', overwrite=True)
-    
+
 if __name__ == "__main__":
 if __name__ == "__main__":
     main()
     main()

+ 18 - 14
lib/python/pygrass/vector/__init__.py

@@ -5,7 +5,7 @@ Created on Tue Jul 17 08:51:53 2012
 @author: pietro
 @author: pietro
 """
 """
 import grass.lib.vector as libvect
 import grass.lib.vector as libvect
-from vector_type import VTYPE
+from .vector_type import VTYPE
 from os.path import join, exists
 from os.path import join, exists
 
 
 #
 #
@@ -14,11 +14,11 @@ from os.path import join, exists
 from grass.pygrass.errors import GrassError, must_be_open
 from grass.pygrass.errors import GrassError, must_be_open
 from grass.pygrass.gis import Location
 from grass.pygrass.gis import Location
 
 
-from geometry import GEOOBJ as _GEOOBJ
-from geometry import read_line, read_next_line
-from geometry import Area as _Area
-from abstract import Info
-from basic import Bbox, Cats, Ilist
+from .geometry import GEOOBJ as _GEOOBJ
+from .geometry import read_line, read_next_line
+from .geometry import Area as _Area
+from .abstract import Info
+from .basic import Bbox, Cats, Ilist
 
 
 
 
 _NUMOF = {"areas": libvect.Vect_get_num_areas,
 _NUMOF = {"areas": libvect.Vect_get_num_areas,
@@ -276,7 +276,7 @@ class VectorTopo(Vector):
             #import pdb; pdb.set_trace()
             #import pdb; pdb.set_trace()
             #Get the start, stop, and step from the slice
             #Get the start, stop, and step from the slice
             return [self.read(indx + 1)
             return [self.read(indx + 1)
-                    for indx in xrange(*key.indices(len(self)))]
+                    for indx in range(*key.indices(len(self)))]
         elif isinstance(key, int):
         elif isinstance(key, int):
             return self.read(key)
             return self.read(key)
         else:
         else:
@@ -389,7 +389,7 @@ class VectorTopo(Vector):
         """
         """
         if vtype in _GEOOBJ.keys():
         if vtype in _GEOOBJ.keys():
             if _GEOOBJ[vtype] is not None:
             if _GEOOBJ[vtype] is not None:
-                ids = (indx for indx in xrange(1, self.number_of(vtype) + 1))
+                ids = (indx for indx in range(1, self.number_of(vtype) + 1))
                 if idonly:
                 if idonly:
                     return ids
                     return ids
                 return (_GEOOBJ[vtype](v_id=indx, c_mapinfo=self.c_mapinfo,
                 return (_GEOOBJ[vtype](v_id=indx, c_mapinfo=self.c_mapinfo,
@@ -422,7 +422,7 @@ class VectorTopo(Vector):
         libvect.Vect_rewind(self.c_mapinfo)
         libvect.Vect_rewind(self.c_mapinfo)
 
 
     @must_be_open
     @must_be_open
-    def cat(self, cat_id, vtype, layer=None, generator=False):
+    def cat(self, cat_id, vtype, layer=None, generator=False, geo=None):
         """Return the geometry features with category == cat_id.
         """Return the geometry features with category == cat_id.
 
 
         Parameters
         Parameters
@@ -436,18 +436,22 @@ class VectorTopo(Vector):
         generator : bool, optional
         generator : bool, optional
             If True return a generator otherwise it return a list of features.
             If True return a generator otherwise it return a list of features.
         """
         """
-        if vtype not in _GEOOBJ:
+        if geo is None and vtype not in _GEOOBJ:
             keys = "', '".join(sorted(_GEOOBJ.keys()))
             keys = "', '".join(sorted(_GEOOBJ.keys()))
             raise ValueError("vtype not supported, use one of: '%s'" % keys)
             raise ValueError("vtype not supported, use one of: '%s'" % keys)
-        Obj = _GEOOBJ[vtype]
+        Obj = _GEOOBJ[vtype] if geo is None else geo
         ilist = Ilist()
         ilist = Ilist()
         libvect.Vect_cidx_find_all(self.c_mapinfo,
         libvect.Vect_cidx_find_all(self.c_mapinfo,
                                    layer if layer else self.layer,
                                    layer if layer else self.layer,
                                    Obj.gtype, cat_id, ilist.c_ilist)
                                    Obj.gtype, cat_id, ilist.c_ilist)
         if generator:
         if generator:
-            return (Obj(v_id=v_id, c_mapinfo=self.c_mapinfo) for v_id in ilist)
+            return (read_line(feature_id=v_id, c_mapinfo=self.c_mapinfo,
+                              table=self.table, writable=self.writable)
+                    for v_id in ilist)
         else:
         else:
-            return [Obj(v_id=v_id, c_mapinfo=self.c_mapinfo) for v_id in ilist]
+            return [read_line(feature_id=v_id, c_mapinfo=self.c_mapinfo,
+                              table=self.table, writable=self.writable)
+                    for v_id in ilist]
 
 
     @must_be_open
     @must_be_open
     def read(self, feature_id):
     def read(self, feature_id):
@@ -549,4 +553,4 @@ class VectorTopo(Vector):
         occupied by spatial index is released"""
         occupied by spatial index is released"""
         if release:
         if release:
             libvect.Vect_set_release_support(self.c_mapinfo)
             libvect.Vect_set_release_support(self.c_mapinfo)
-        super(VectorTopo, self).close()
+        super(VectorTopo, self).close(build=build)

+ 5 - 7
lib/python/pygrass/vector/abstract.py

@@ -7,12 +7,12 @@ Created on Fri Aug 17 17:24:03 2012
 import ctypes
 import ctypes
 import datetime
 import datetime
 import grass.lib.vector as libvect
 import grass.lib.vector as libvect
-from vector_type import MAPTYPE
+from .vector_type import MAPTYPE
 
 
 from grass.pygrass import functions
 from grass.pygrass import functions
 from grass.pygrass.errors import GrassError, OpenError, must_be_open
 from grass.pygrass.errors import GrassError, OpenError, must_be_open
-from table import DBlinks, Link
-from find import PointFinder, BboxFinder, PolygonFinder
+from .table import DBlinks, Link
+from .find import PointFinder, BboxFinder, PolygonFinder
 
 
 
 
 def is_open(c_mapinfo):
 def is_open(c_mapinfo):
@@ -78,8 +78,8 @@ class Info(object):
 
 
     """
     """
     def __init__(self, name, mapset='', layer=None, mode='r'):
     def __init__(self, name, mapset='', layer=None, mode='r'):
-        self._name = None
-        self._mapset = None
+        self._name = ''
+        self._mapset = ''
         # Set map name and mapset
         # Set map name and mapset
         self.name = name
         self.name = name
         self.mapset = mapset
         self.mapset = mapset
@@ -121,8 +121,6 @@ class Info(object):
         """Private method to change the Vector name"""
         """Private method to change the Vector name"""
         if mapset:
         if mapset:
             self._mapset = mapset
             self._mapset = mapset
-        else:
-            self._mapset = ''
 
 
     mapset = property(fget=_get_mapset, fset=_set_mapset)
     mapset = property(fget=_get_mapset, fset=_set_mapset)
 
 

+ 7 - 7
lib/python/pygrass/vector/basic.py

@@ -186,7 +186,7 @@ class BoxList(object):
         self.c_boxlist.contents.box[indx] = bbox
         self.c_boxlist.contents.box[indx] = bbox
 
 
     def __iter__(self):
     def __iter__(self):
-        return (self.__getitem__(box_id) for box_id in xrange(self.__len__()))
+        return (self.__getitem__(box_id) for box_id in range(self.__len__()))
 
 
     def __str__(self):
     def __str__(self):
         return self.__repr__()
         return self.__repr__()
@@ -297,7 +297,7 @@ class Ilist(object):
             #import pdb; pdb.set_trace()
             #import pdb; pdb.set_trace()
             #Get the start, stop, and step from the slice
             #Get the start, stop, and step from the slice
             return [self.c_ilist.contents.value[indx]
             return [self.c_ilist.contents.value[indx]
-                    for indx in xrange(*key.indices(len(self)))]
+                    for indx in range(*key.indices(len(self)))]
         elif isinstance(key, int):
         elif isinstance(key, int):
             if key < 0:  # Handle negative indices
             if key < 0:  # Handle negative indices
                 key += self.c_ilist.contents.n_values
                 key += self.c_ilist.contents.n_values
@@ -316,7 +316,7 @@ class Ilist(object):
         return self.c_ilist.contents.n_values
         return self.c_ilist.contents.n_values
 
 
     def __iter__(self):
     def __iter__(self):
-        return (self.c_ilist.contents.value[i] for i in xrange(self.__len__()))
+        return (self.c_ilist.contents.value[i] for i in range(self.__len__()))
 
 
     def __repr__(self):
     def __repr__(self):
         return "Ilist(%r)" % [i for i in self.__iter__()]
         return "Ilist(%r)" % [i for i in self.__iter__()]
@@ -395,12 +395,12 @@ class Cats(object):
     @property
     @property
     def layer(self):
     def layer(self):
         field = self.c_cats.contents.field
         field = self.c_cats.contents.field
-        return [field[i] for i in xrange(self.n_cats)]
+        return [field[i] for i in range(self.n_cats)]
 
 
     @property
     @property
     def cat(self):
     def cat(self):
         cat = self.c_cats.contents.cat
         cat = self.c_cats.contents.cat
-        return [cat[i] for i in xrange(self.n_cats)]
+        return [cat[i] for i in range(self.n_cats)]
 
 
     @property
     @property
     def n_cats(self):
     def n_cats(self):
@@ -490,13 +490,13 @@ class CatsList(object):
     def min(self):
     def min(self):
         """Return the minimum value"""
         """Return the minimum value"""
         min_values = self.c_cat_list.contents.min
         min_values = self.c_cat_list.contents.min
-        return [min_values[i] for i in xrange(self.n_ranges)]
+        return [min_values[i] for i in range(self.n_ranges)]
 
 
     @property
     @property
     def max(self):
     def max(self):
         """Return the maximum value"""
         """Return the maximum value"""
         max_values = self.c_cat_list.contents.max
         max_values = self.c_cat_list.contents.max
-        return [max_values[i] for i in xrange(self.n_ranges)]
+        return [max_values[i] for i in range(self.n_ranges)]
 
 
     def __init__(self, c_cat_list=None):
     def __init__(self, c_cat_list=None):
         self.c_cat_list = c_cat_list if c_cat_list \
         self.c_cat_list = c_cat_list if c_cat_list \

+ 3 - 3
lib/python/pygrass/vector/find.py

@@ -8,8 +8,8 @@ import grass.lib.vector as libvect
 
 
 from grass.pygrass.errors import must_be_open
 from grass.pygrass.errors import must_be_open
 
 
-from basic import Ilist, BoxList
-from geometry import read_line, Isle, Area, Point
+from .basic import Ilist, BoxList
+from .geometry import read_line, Isle, Area, Point
 
 
 
 
 class AbstractFinder(object):
 class AbstractFinder(object):
@@ -27,7 +27,7 @@ class AbstractFinder(object):
 
 
     def is_open(self):
     def is_open(self):
         """Check if the vector map is open or not"""
         """Check if the vector map is open or not"""
-        import abstract
+        from . import abstract
         return abstract.is_open(self.c_mapinfo)
         return abstract.is_open(self.c_mapinfo)
 
 
 
 

+ 11 - 8
lib/python/pygrass/vector/geometry.py

@@ -15,8 +15,8 @@ import grass.lib.vector as libvect
 
 
 from grass.pygrass.errors import GrassError
 from grass.pygrass.errors import GrassError
 
 
-from basic import Ilist, Bbox, Cats
-import sql
+from .basic import Ilist, Bbox, Cats
+from . import sql
 
 
 
 
 WKT = {'POINT\((.*)\)': 'point',  # 'POINT\(\s*([+-]*\d+\.*\d*)+\s*\)'
 WKT = {'POINT\((.*)\)': 'point',  # 'POINT\(\s*([+-]*\d+\.*\d*)+\s*\)'
@@ -159,9 +159,12 @@ class Attrs(object):
 
 
         """
         """
         #SELECT {cols} FROM {tname} WHERE {condition};
         #SELECT {cols} FROM {tname} WHERE {condition};
-        cur = self.table.execute(sql.SELECT_WHERE.format(cols=key,
+        try:
+            cur = self.table.execute(sql.SELECT_WHERE.format(cols=key,
                                                          tname=self.table.name,
                                                          tname=self.table.name,
                                                          condition=self.cond))
                                                          condition=self.cond))
+        except:
+            import ipdb; ipdb.set_trace()
         results = cur.fetchone()
         results = cur.fetchone()
         if results is not None:
         if results is not None:
             return results[0] if len(results) == 1 else results
             return results[0] if len(results) == 1 else results
@@ -316,7 +319,7 @@ class Point(Geo):
         False
         False
         >>> pnt
         >>> pnt
         Point(0.000000, 0.000000, 0.000000)
         Point(0.000000, 0.000000, 0.000000)
-        >>> print pnt
+        >>> print(pnt)
         POINT(0.000000, 0.000000, 0.000000)
         POINT(0.000000, 0.000000, 0.000000)
 
 
     ..
     ..
@@ -547,7 +550,7 @@ class Line(Geo):
             return [Point(self.c_points.contents.x[indx],
             return [Point(self.c_points.contents.x[indx],
                           self.c_points.contents.y[indx],
                           self.c_points.contents.y[indx],
                     None if self.is2D else self.c_points.contents.z[indx])
                     None if self.is2D else self.c_points.contents.z[indx])
-                    for indx in xrange(*key.indices(len(self)))]
+                    for indx in range(*key.indices(len(self)))]
         elif isinstance(key, int):
         elif isinstance(key, int):
             if key < 0:  # Handle negative indices
             if key < 0:  # Handle negative indices
                 key += self.c_points.contents.n_points
                 key += self.c_points.contents.n_points
@@ -1017,7 +1020,7 @@ class Line(Geo):
         return Area(boundary=Line(c_points=p_bound.contents),
         return Area(boundary=Line(c_points=p_bound.contents),
                     centroid=self[0],
                     centroid=self[0],
                     isles=[Line(c_points=pp_isle[i].contents)
                     isles=[Line(c_points=pp_isle[i].contents)
-                           for i in xrange(n_isles.contents.value)])
+                           for i in range(n_isles.contents.value)])
 
 
     def reset(self):
     def reset(self):
         """Reset line, using `Vect_reset_line` C function. ::
         """Reset line, using `Vect_reset_line` C function. ::
@@ -1053,7 +1056,7 @@ class Boundary(Line):
         super(Boundary, self).__init__(**kargs)
         super(Boundary, self).__init__(**kargs)
         self.c_left = ctypes.pointer(ctypes.c_int())
         self.c_left = ctypes.pointer(ctypes.c_int())
         self.c_right = ctypes.pointer(ctypes.c_int())
         self.c_right = ctypes.pointer(ctypes.c_int())
-        self.get_left_right()
+        #self.get_left_right()
 
 
     @property
     @property
     def left_id(self):
     def left_id(self):
@@ -1395,7 +1398,7 @@ class Area(Geo):
         return Area(boundary=Line(c_points=p_bound.contents),
         return Area(boundary=Line(c_points=p_bound.contents),
                     centroid=self.centroid,
                     centroid=self.centroid,
                     isles=[Line(c_points=pp_isle[i].contents)
                     isles=[Line(c_points=pp_isle[i].contents)
-                           for i in xrange(n_isles.contents.value)])
+                           for i in range(n_isles.contents.value)])
 
 
     def boundaries(self, ilist=False):
     def boundaries(self, ilist=False):
         """Creates list of boundaries for given area.
         """Creates list of boundaries for given area.

+ 18 - 10
lib/python/pygrass/vector/table.py

@@ -7,7 +7,14 @@ Created on Wed Aug  8 15:29:21 2012
 
 
 
 
 """
 """
+from __future__ import (nested_scopes, generators, division, absolute_import,
+                        with_statement, print_function, unicode_literals)
+
 import os
 import os
+import sys
+
+long = int if sys.version_info.major == 3 else long
+
 import ctypes
 import ctypes
 import numpy as np
 import numpy as np
 from sqlite3 import OperationalError
 from sqlite3 import OperationalError
@@ -24,7 +31,7 @@ from grass.pygrass.functions import table_exist
 from grass.script.db import db_table_in_vector
 from grass.script.db import db_table_in_vector
 from grass.script.core import warning
 from grass.script.core import warning
 
 
-import sql
+from . import sql
 
 
 
 
 DRIVERS = ('sqlite', 'pg')
 DRIVERS = ('sqlite', 'pg')
@@ -724,12 +731,12 @@ class Link(object):
 
 
         ..
         ..
         """
         """
-        print "layer:    ", self.layer
-        print "name:     ", self.name
-        print "table:    ", self.table_name
-        print "key:      ", self.key
-        print "database: ", self.database
-        print "driver:   ", self.driver
+        print("layer:    ", self.layer)
+        print("name:     ", self.name)
+        print("table:    ", self.table_name)
+        print("key:      ", self.key)
+        print("database: ", self.database)
+        print("driver:   ", self.driver)
 
 
 
 
 class DBlinks(object):
 class DBlinks(object):
@@ -756,7 +763,7 @@ class DBlinks(object):
 
 
     def __iter__(self):
     def __iter__(self):
         return (self.by_index(i)
         return (self.by_index(i)
-                for i in xrange(self.num_dblinks()))
+                for i in range(self.num_dblinks()))
 
 
     def __getitem__(self, item):
     def __getitem__(self, item):
         """
         """
@@ -904,7 +911,7 @@ class Table(object):
 
 
     def __iter__(self):
     def __iter__(self):
         cur = self.execute()
         cur = self.execute()
-        return (cur.fetchone() for _ in xrange(self.__len__()))
+        return (cur.fetchone() for _ in range(self.__len__()))
 
 
     def __len__(self):
     def __len__(self):
         """Return the number of rows"""
         """Return the number of rows"""
@@ -965,6 +972,7 @@ class Table(object):
                 return cur.executemany(sqlc, values)
                 return cur.executemany(sqlc, values)
             return cur.execute(sqlc)
             return cur.execute(sqlc)
         except:
         except:
+            #import ipdb; ipdb.set_trace()
             raise ValueError("The SQL is not correct:\n%r" % sqlc)
             raise ValueError("The SQL is not correct:\n%r" % sqlc)
 
 
     def exist(self, cursor=None):
     def exist(self, cursor=None):
@@ -1004,6 +1012,6 @@ class Table(object):
                                                   coldef=coldef))
                                                   coldef=coldef))
                 self.conn.commit()
                 self.conn.commit()
             else:
             else:
-                print "The table: %s already exist." % self.name
+                print("The table: %s already exist." % self.name)
         cur.close()
         cur.close()
         self.columns.update_odict()
         self.columns.update_odict()

+ 1 - 1
lib/python/pygrass/vector/vector_type.py

@@ -6,7 +6,7 @@ Created on Wed Jul 18 10:49:26 2012
 """
 """
 
 
 import grass.lib.vector as libvect
 import grass.lib.vector as libvect
-import geometry as geo
+from . import geometry as geo
 
 
 MAPTYPE = {libvect.GV_FORMAT_NATIVE:     "native",
 MAPTYPE = {libvect.GV_FORMAT_NATIVE:     "native",
            libvect.GV_FORMAT_OGR:        "OGR",
            libvect.GV_FORMAT_OGR:        "OGR",