[GRASS-SVN] r68352 - grass/trunk/lib/python/script

svn_grass at osgeo.org svn_grass at osgeo.org
Mon May 2 09:07:20 PDT 2016


Author: zarch
Date: 2016-05-02 09:07:20 -0700 (Mon, 02 May 2016)
New Revision: 68352

Modified:
   grass/trunk/lib/python/script/db.py
   grass/trunk/lib/python/script/raster.py
   grass/trunk/lib/python/script/task.py
   grass/trunk/lib/python/script/vector.py
Log:
script: fix python 2 and python 3 syntax

Modified: grass/trunk/lib/python/script/db.py
===================================================================
--- grass/trunk/lib/python/script/db.py	2016-05-02 16:07:13 UTC (rev 68351)
+++ grass/trunk/lib/python/script/db.py	2016-05-02 16:07:20 UTC (rev 68352)
@@ -163,8 +163,7 @@
         fatal(_("Fetching data failed"))
 
     ofile = open(fname)
-    result = map(lambda x: tuple(x.rstrip(os.linesep).split(args['sep'])),
-                 ofile.readlines())
+    result = [tuple(x.rstrip(os.linesep).split(args['sep'])) for x in ofile.readlines()]
     ofile.close()
     try_remove(fname)
 
@@ -190,7 +189,7 @@
     used = []
     vects = list_strings('vect')
     for vect in vects:
-        for f in vector_db(vect, stderr=nuldev).itervalues():
+        for f in vector_db(vect, stderr=nuldev).values():
             if not f:
                 continue
             if f['table'] == table:

Modified: grass/trunk/lib/python/script/raster.py
===================================================================
--- grass/trunk/lib/python/script/raster.py	2016-05-02 16:07:13 UTC (rev 68351)
+++ grass/trunk/lib/python/script/raster.py	2016-05-02 16:07:20 UTC (rev 68352)
@@ -21,7 +21,6 @@
 
 import os
 import string
-import types
 import time
 
 from .core import *
@@ -29,6 +28,14 @@
 from .utils import float_or_dms, parse_key_val
 
 
+try:
+    from builtins import unicode
+    bytes = str
+except ImportError:
+    # python3
+    unicode = str
+
+
 def raster_history(map):
     """Set the command history for a raster map to the command used to
     invoke the script (interface to `r.support`).
@@ -161,13 +168,13 @@
                        query
     :param env:
     """
-    if type(map) in (types.StringType, types.UnicodeType):
+    if isinstance(map, (bytes, unicode)):
         map_list = [map]
     else:
         map_list = map
 
     coord_list = list()
-    if type(coord) is types.TupleType:
+    if isinstance(coord, tuple):
         coord_list.append('%f,%f' % (coord[0], coord[1]))
     else:
         for e, n in coord:

Modified: grass/trunk/lib/python/script/task.py
===================================================================
--- grass/trunk/lib/python/script/task.py	2016-05-02 16:07:13 UTC (rev 68351)
+++ grass/trunk/lib/python/script/task.py	2016-05-02 16:07:20 UTC (rev 68352)
@@ -20,7 +20,15 @@
 import re
 import types
 import string
+
 try:
+    from builtins import unicode
+    bytes = str
+except ImportError:
+    # python3
+    unicode = str
+
+try:
     import xml.etree.ElementTree as etree
 except ImportError:
     import elementtree.ElementTree as etree # Python <= 2.4
@@ -32,8 +40,8 @@
 else:
     ETREE_EXCEPTIONS = (expat.ExpatError)
 
-from utils import encode, decode, split
-from core import *
+from .utils import encode, decode, split
+from .core import *
 
 
 class grassTask:
@@ -152,10 +160,10 @@
                 val = p[element]
                 if val is None:
                     continue
-                if type(val) in (types.ListType, types.TupleType):
+                if isinstance(val, (list, tuple)):
                     if value in val:
                         return p
-                elif type(val) ==  types.StringType:
+                elif isinstance(val, (bytes, unicode)):
                     if p[element][:len(value)] ==  value:
                         return p
                 else:
@@ -165,8 +173,8 @@
             pass
 
         if raiseError:
-            raise ValueError, _("Parameter element '%(element)s' not found: '%(value)s'") % \
-                { 'element' : element, 'value' : value }
+            raise ValueError(_("Parameter element '%(element)s' not found: '%(value)s'") % \
+                { 'element' : element, 'value' : value })
         else:
             return None
 
@@ -180,7 +188,7 @@
         for f in self.flags:
             if f['name'] == aFlag:
                 return f
-        raise ValueError, _("Flag not found: %s") % aFlag
+        raise ValueError(_("Flag not found: %s") % aFlag)
 
     def get_cmd_error(self):
         """Get error string produced by get_cmd(ignoreErrors = False)
@@ -242,7 +250,7 @@
 
         errList = self.get_cmd_error()
         if ignoreErrors is False and errList:
-            raise ValueError, '\n'.join(errList)
+            raise ValueError('\n'.join(errList))
 
         return cmd
 
@@ -492,12 +500,12 @@
                 del sys.path[0]  # remove gui/scripts from the path
 
         if p.returncode != 0:
-            raise ScriptError, _("Unable to fetch interface description for command '%(cmd)s'."
-                                 "\n\nDetails: %(det)s") % {'cmd': cmd, 'det': cmderr}
+            raise ScriptError(_("Unable to fetch interface description for command '%(cmd)s'."
+                                 "\n\nDetails: %(det)s") % {'cmd': cmd, 'det': cmderr})
 
     except OSError as e:
-        raise ScriptError, _("Unable to fetch interface description for command '%(cmd)s'."
-                             "\n\nDetails: %(det)s") % {'cmd': cmd, 'det': e}
+        raise ScriptError(_("Unable to fetch interface description for command '%(cmd)s'."
+                             "\n\nDetails: %(det)s") % {'cmd': cmd, 'det': e})
 
     desc = cmdout.replace('grass-interface.dtd',
                           os.path.join(os.getenv('GISBASE'),
@@ -624,7 +632,7 @@
         if flag in cmd[1] and cmd[1][flag] is True:
             cmdList.append('--' + flag)
 
-    for k, v in cmd[1].iteritems():
+    for k, v in cmd[1].items():
         if k in ('flags', 'help', 'verbose', 'quiet', 'overwrite'):
             continue
         cmdList.append('%s=%s' % (k, v))

Modified: grass/trunk/lib/python/script/vector.py
===================================================================
--- grass/trunk/lib/python/script/vector.py	2016-05-02 16:07:13 UTC (rev 68351)
+++ grass/trunk/lib/python/script/vector.py	2016-05-02 16:07:20 UTC (rev 68352)
@@ -22,8 +22,11 @@
 
 try:
     import __builtin__
+    bytes = str
 except ImportError:
+    # python3
     import builtins as __builtin__
+    unicode = str
 
 from .utils import parse_key_val
 from .core import *
@@ -331,7 +334,7 @@
         locale = os.environ["LC_ALL"]
         os.environ["LC_ALL"] = "C"
 
-    if type(map) in (types.StringType, types.UnicodeType):
+    if isinstance(map, (bytes, unicode)):
         map_list = [map]
     else:
         map_list = map
@@ -339,7 +342,7 @@
     layer_list = ['-1'] * len(map_list)
 
     coord_list = list()
-    if type(coord) is types.TupleType:
+    if isinstance(coord, tuple):
         coord_list.append('%f,%f' % (coord[0], coord[1]))
     else:
         for e, n in coord:



More information about the grass-commit mailing list