[GRASS-SVN] r62379 - in grass/branches/releasebranch_7_0: gui/wxpython lib/python lib/python/exceptions lib/python/pygrass lib/python/pygrass/messages lib/python/pygrass/modules/interface lib/python/script lib/python/temporal

svn_grass at osgeo.org svn_grass at osgeo.org
Sun Oct 26 08:48:02 PDT 2014


Author: zarch
Date: 2014-10-26 08:48:02 -0700 (Sun, 26 Oct 2014)
New Revision: 62379

Added:
   grass/branches/releasebranch_7_0/lib/python/exceptions/
   grass/branches/releasebranch_7_0/lib/python/exceptions/testsuite/
Modified:
   grass/branches/releasebranch_7_0/gui/wxpython/wxgui.py
   grass/branches/releasebranch_7_0/lib/python/Makefile
   grass/branches/releasebranch_7_0/lib/python/exceptions/__init__.py
   grass/branches/releasebranch_7_0/lib/python/pygrass/errors.py
   grass/branches/releasebranch_7_0/lib/python/pygrass/messages/__init__.py
   grass/branches/releasebranch_7_0/lib/python/pygrass/modules/interface/module.py
   grass/branches/releasebranch_7_0/lib/python/script/core.py
   grass/branches/releasebranch_7_0/lib/python/temporal/abstract_dataset.py
   grass/branches/releasebranch_7_0/lib/python/temporal/temporal_algebra.py
Log:
Add exceptions module in python library, commit backported: r61187, r61220, r61959, r62358

Modified: grass/branches/releasebranch_7_0/gui/wxpython/wxgui.py
===================================================================
--- grass/branches/releasebranch_7_0/gui/wxpython/wxgui.py	2014-10-24 22:48:44 UTC (rev 62378)
+++ grass/branches/releasebranch_7_0/gui/wxpython/wxgui.py	2014-10-26 15:48:02 UTC (rev 62379)
@@ -1,4 +1,4 @@
-"""!
+"""
 @package wxgui
 
 @brief Main Python application for GRASS wxPython GUI
@@ -25,6 +25,8 @@
 from core import globalvar
 from core.utils import _
 
+from grass.exceptions import Usage
+
 import wx
 try:
     import wx.lib.agw.advancedsplash as SC
@@ -33,6 +35,7 @@
 
 from lmgr.frame import GMFrame
 
+
 class GMApp(wx.App):
     def __init__(self, workspace = None):
         """!Main GUI class.
@@ -40,28 +43,28 @@
         @param workspace path to the workspace file
         """
         self.workspaceFile = workspace
-        
+
         # call parent class initializer
         wx.App.__init__(self, False)
-        
+
         self.locale = wx.Locale(language = wx.LANGUAGE_DEFAULT)
-        
+
     def OnInit(self):
         """!Initialize all available image handlers
-        
+
         @return True
         """
         if not globalvar.CheckWxVersion([2, 9]):
             wx.InitAllImageHandlers()
-        
+
         # create splash screen
         introImagePath = os.path.join(globalvar.IMGDIR, "silesia_splash.png")
         introImage     = wx.Image(introImagePath, wx.BITMAP_TYPE_PNG)
         introBmp       = introImage.ConvertToBitmap()
         if SC and sys.platform != 'darwin':
-            # AdvancedSplash is buggy on the Mac as of 2.8.12.1 
+            # AdvancedSplash is buggy on the Mac as of 2.8.12.1
             # and raises annoying (though seemingly harmless) errors everytime the GUI is started
-            splash = SC.AdvancedSplash(bitmap = introBmp, 
+            splash = SC.AdvancedSplash(bitmap = introBmp,
                                        timeout = 2000, parent = None, id = wx.ID_ANY)
             splash.SetText(_('Starting GRASS GUI...'))
             splash.SetTextColour(wx.Colour(45, 52, 27))
@@ -71,21 +74,18 @@
         else:
             wx.SplashScreen (bitmap = introBmp, splashStyle = wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,
                              milliseconds = 2000, parent = None, id = wx.ID_ANY)
-        
+
         wx.Yield()
-        
+
         # create and show main frame
         mainframe = GMFrame(parent = None, id = wx.ID_ANY,
                             workspace = self.workspaceFile)
-        
+
         mainframe.Show()
         self.SetTopWindow(mainframe)
-        
+
         return True
 
-class Usage(Exception):
-    def __init__(self, msg):
-        self.msg = msg
 
 def printHelp():
     """!Print program help"""
@@ -95,13 +95,14 @@
     print >> sys.stderr, " -w\t--workspace file\tWorkspace file to load"
     sys.exit(1)
 
+
 def process_opt(opts, args):
     """!Process command-line arguments"""
     workspaceFile = None
     for o, a in opts:
         if o in ("-h", "--help"):
             printHelp()
-            
+
         if o in ("-w", "--workspace"):
             if a != '':
                 workspaceFile = str(a)
@@ -110,8 +111,9 @@
 
     return (workspaceFile,)
 
+
 def main(argv = None):
-    
+
     if argv is None:
         argv = sys.argv
     try:
@@ -120,19 +122,19 @@
                                        ["help", "workspace"])
         except getopt.error as msg:
             raise Usage(msg)
-    
+
     except Usage as err:
         print >> sys.stderr, err.msg
         print >> sys.stderr, "for help use --help"
         printHelp()
-    
+
     workspaceFile = process_opt(opts, args)[0]
-    
+
     app = GMApp(workspaceFile)
     # suppress wxPython logs
     q = wx.LogNull()
-    
+
     app.MainLoop()
-    
+
 if __name__ == "__main__":
     sys.exit(main())

Modified: grass/branches/releasebranch_7_0/lib/python/Makefile
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/Makefile	2014-10-24 22:48:44 UTC (rev 62378)
+++ grass/branches/releasebranch_7_0/lib/python/Makefile	2014-10-26 15:48:02 UTC (rev 62379)
@@ -5,7 +5,7 @@
 
 PYDIR = $(ETC)/python/grass
 
-SUBDIRS = script ctypes temporal pygrass pydispatch imaging
+SUBDIRS = exceptions script ctypes temporal pygrass pydispatch imaging
 
 default: $(PYDIR)/__init__.py
 	$(MAKE) subdirs

Modified: grass/branches/releasebranch_7_0/lib/python/exceptions/__init__.py
===================================================================
--- grass/trunk/lib/python/exceptions/__init__.py	2014-07-08 12:09:32 UTC (rev 61187)
+++ grass/branches/releasebranch_7_0/lib/python/exceptions/__init__.py	2014-10-26 15:48:02 UTC (rev 62379)
@@ -1,4 +1,6 @@
 # -*- coding: utf-8 -*-
+"""GRASS GIS interface to Python exceptions"""
+import subprocess
 
 
 class DBError(Exception):
@@ -30,8 +32,46 @@
 
 
 class ScriptError(Exception):
-    pass
+    """Raised during script execution. ::
 
+        >>> error = ScriptError('My error message!')
+        >>> error.value
+        'My error message!'
+        >>> print(error)
+        My error message!
+    """
+    def __init__(self, value):
+        self.value = value
 
+    def __str__(self):
+        return str(self.value)
+
+
 class Usage(Exception):
     pass
+
+
+# TODO: we inherit from subprocess to be aligned with check_call but it is needed?
+class CalledModuleError(subprocess.CalledProcessError):
+    """Raised when a called module ends with error (non-zero return code)
+
+    :param module: module name
+    :param code: some code snipped which contains parameters
+    :param rc: process returncode
+    :param error: errors provided by the module (stderr)
+    """
+    def __init__(self, module, code, returncode, errors=None):
+        super(CalledModuleError, self).__init__(returncode, module)
+        msg = _("Module run %s %s ended with error") % (module, code)
+        msg += _("\nProcess ended with non-zero return code %s") % returncode
+        if errors:
+            msg += _(". See the following errors:\n%s") % errors
+        else:
+            # here could be written "above" but it wouldn't work in some cases
+            # e.g., for testing framework
+            msg += _(". See errors in the (error) output.")
+        self.msg = msg
+        # TODO: handle other parameters
+
+    def __str__(self):
+        return self.msg

Modified: grass/branches/releasebranch_7_0/lib/python/pygrass/errors.py
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/pygrass/errors.py	2014-10-24 22:48:44 UTC (rev 62378)
+++ grass/branches/releasebranch_7_0/lib/python/pygrass/errors.py	2014-10-26 15:48:02 UTC (rev 62379)
@@ -5,37 +5,13 @@
 @author: pietro
 """
 from functools import wraps
-from grass.pygrass.messages import get_msgr
 
+from grass.exceptions import (FlagError, ParameterError, DBError,
+                              GrassError, OpenError)
 
-class AbstractError(Exception):
-    def __init__(self, value):
-        self.value = value
+from grass.pygrass.messages import get_msgr
 
-    def __str__(self):
-        return repr(self.value)
 
-
-class ParameterError(Exception):
-    pass
-
-
-class FlagError(Exception):
-    pass
-
-
-class DBError(AbstractError):
-    pass
-
-
-class GrassError(AbstractError):
-    pass
-
-
-class OpenError(AbstractError):
-    pass
-
-
 def must_be_open(method):
 
     @wraps(method)

Modified: grass/branches/releasebranch_7_0/lib/python/pygrass/messages/__init__.py
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/pygrass/messages/__init__.py	2014-10-24 22:48:44 UTC (rev 62378)
+++ grass/branches/releasebranch_7_0/lib/python/pygrass/messages/__init__.py	2014-10-26 15:48:02 UTC (rev 62379)
@@ -14,21 +14,12 @@
 @author Soeren Gebbert
 """
 import sys
-import grass.lib.gis as libgis
 from multiprocessing import Process, Lock, Pipe
 
+import grass.lib.gis as libgis
+from grass.exceptions import FatalError
 
-class FatalError(Exception):
-    """This error will be raised in case raise_on_error was set True
-       when creating the messenger object.
-    """
-    def __init__(self, msg):
-        self.value = msg
 
-    def __str__(self):
-        return self.value
-
-
 def message_server(lock, conn):
     """The GRASS message server function designed to be a target for
        multiprocessing.Process

Modified: grass/branches/releasebranch_7_0/lib/python/pygrass/modules/interface/module.py
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/pygrass/modules/interface/module.py	2014-10-24 22:48:44 UTC (rev 62378)
+++ grass/branches/releasebranch_7_0/lib/python/pygrass/modules/interface/module.py	2014-10-26 15:48:02 UTC (rev 62379)
@@ -361,25 +361,21 @@
             for flg in kargs['flags']:
                 self.flags[flg].value = True
             del(kargs['flags'])
-        if 'run_' in kargs:
-            self.run_ = kargs['run_']
-            del(kargs['run_'])
-        if 'stdin_' in kargs:
-            self.inputs['stdin'].value = kargs['stdin_']
-            del(kargs['stdin_'])
-        if 'stdout_' in kargs:
-            self.stdout_ = kargs['stdout_']
-            del(kargs['stdout_'])
-        if 'stderr_' in kargs:
-            self.stderr_ = kargs['stderr_']
-            del(kargs['stderr_'])
-        if 'env_' in kargs:
-            self.env_ = kargs['env_']
-            del(kargs['env_'])
-        if 'finish_' in kargs:
-            self.finish_ = kargs['finish_']
-            del(kargs['finish_'])
 
+        # set attributs
+        for key in ('run_', 'env_', 'finish_'):
+            if key in kargs:
+                setattr(self, key, kargs.pop(key))
+
+        # set inputs
+        for key in ('stdin_', ):
+            if key in kargs:
+                self.inputs[key].value = kargs.pop(key)
+        # set outputs
+        for key in ('stdout_', 'stderr_'):
+            if key in kargs:
+                self.outputs[key].value = kargs.pop(key)
+
         #
         # check args
         #
@@ -527,6 +523,9 @@
             self.outputs['stdout'].value = stdout if stdout else ''
             self.outputs['stderr'].value = stderr if stderr else ''
             self.time = time.time() - start
+            #if self.popen.poll():
+            #    raise CalledModuleError(self.popen.returncode, self.get_bash(),
+            #                            {}, stderr)
         return self
 
 ###############################################################################

Modified: grass/branches/releasebranch_7_0/lib/python/script/core.py
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/script/core.py	2014-10-24 22:48:44 UTC (rev 62378)
+++ grass/branches/releasebranch_7_0/lib/python/script/core.py	2014-10-26 15:48:02 UTC (rev 62379)
@@ -34,6 +34,8 @@
 
 from utils import KeyValue, parse_key_val, basename, encode
 
+from grass.exceptions import ScriptError
+
 # i18N
 import gettext
 gettext.install('grasslibs', os.path.join(os.getenv("GISBASE"), 'locale'))
@@ -68,13 +70,6 @@
 STDOUT = subprocess.STDOUT
 
 
-class ScriptError(Exception):
-    def __init__(self, msg):
-        self.value = msg
-
-    def __str__(self):
-        return self.value
-
 raise_on_error = False  # raise exception instead of calling fatal()
 
 
@@ -873,9 +868,25 @@
                 return False
     return True
 
-# interface to g.gisenv
 
+def diff_files(filename_a, filename_b):
+    """!Diffs two text files and returns difference.
 
+    @param filename_a first file path
+    @param filename_b second file path
+
+    @return list of strings
+    """
+    import difflib
+    differ = difflib.Differ()
+    fh_a = open(filename_a, 'r')
+    fh_b = open(filename_b, 'r')
+    result = list(differ.compare(fh_a.readlines(),
+                                 fh_b.readlines()))
+    return result
+
+
+# interface to g.gisenv
 def gisenv():
     """!Returns the output from running g.gisenv (with no arguments), as a
     dictionary. Example:

Modified: grass/branches/releasebranch_7_0/lib/python/temporal/abstract_dataset.py
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/temporal/abstract_dataset.py	2014-10-24 22:48:44 UTC (rev 62378)
+++ grass/branches/releasebranch_7_0/lib/python/temporal/abstract_dataset.py	2014-10-26 15:48:02 UTC (rev 62379)
@@ -22,16 +22,8 @@
 from temporal_topology_dataset_connector import *
 from spatial_topology_dataset_connector import *
 
+from grass.exceptions import ImplementationError
 
-class ImplementationError(Exception):
-    """!Exception raised for the calling of methods that should be implemented in
-       sub classes.
-    """
-    def __init__(self, msg):
-        self.msg = msg
-    def __str__(self):
-        return repr(self.msg)
-
 ###############################################################################
 
 class AbstractDataset(SpatialTopologyDatasetConnector, TemporalTopologyDatasetConnector):

Modified: grass/branches/releasebranch_7_0/lib/python/temporal/temporal_algebra.py
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/temporal/temporal_algebra.py	2014-10-24 22:48:44 UTC (rev 62378)
+++ grass/branches/releasebranch_7_0/lib/python/temporal/temporal_algebra.py	2014-10-26 15:48:02 UTC (rev 62379)
@@ -396,6 +396,8 @@
 from open_stds import *
 import copy
 
+from grass.exceptions import FatalError
+
 ##############################################################################
 
 class TemporalAlgebraLexer(object):
@@ -650,17 +652,10 @@
     def __str__(self):
         return str(self.tfunc) + str(self.compop) + str(self.value)
 
-###############################################################################
 
-class FatalError(Exception):
-    def __init__(self, msg):
-        self.value = msg
-
-    def __str__(self):
-        return self.value
-
 ###############################################################################
 
+
 class TemporalAlgebraParser(object):
     """The temporal algebra class"""
 



More information about the grass-commit mailing list