瀏覽代碼

exceptions: Move exceptions from around the GRASS code to one place

git-svn-id: https://svn.osgeo.org/grass/grass/trunk@61187 15284696-431f-4ddb-bdfa-cd5b030d7da7
Pietro Zambelli 10 年之前
父節點
當前提交
69fecb8622

+ 24 - 22
gui/wxpython/wxgui.py

@@ -1,4 +1,4 @@
-""" 
+"""
 @package wxgui
 
 @brief Main Python application for GRASS wxPython GUI
@@ -25,6 +25,8 @@ import getopt
 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 @@ except ImportError:
 
 from lmgr.frame import GMFrame
 
+
 class GMApp(wx.App):
     def __init__(self, workspace = None):
         """ Main GUI class.
@@ -40,28 +43,28 @@ class GMApp(wx.App):
         :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 @@ class GMApp(wx.App):
         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 @@ def printHelp():
     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 @@ def process_opt(opts, args):
 
     return (workspaceFile,)
 
+
 def main(argv = None):
-    
+
     if argv is None:
         argv = sys.argv
     try:
@@ -120,19 +122,19 @@ def main(argv = None):
                                        ["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())

+ 1 - 1
lib/python/Makefile

@@ -5,7 +5,7 @@ include $(MODULE_TOPDIR)/include/Make/Python.make
 
 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

+ 30 - 0
lib/python/exceptions/Makefile

@@ -0,0 +1,30 @@
+MODULE_TOPDIR=../../..
+
+include $(MODULE_TOPDIR)/include/Make/Other.make
+include $(MODULE_TOPDIR)/include/Make/Python.make
+include $(MODULE_TOPDIR)/include/Make/Doxygen.make
+
+PYDIR = $(ETC)/python
+GDIR = $(PYDIR)/grass
+DSTDIR = $(GDIR)/exceptions
+
+PYFILES := $(patsubst %,$(DSTDIR)/%.py,$(MODULES) __init__)
+PYCFILES := $(patsubst %,$(DSTDIR)/%.pyc,$(MODULES) __init__)
+
+default: $(PYFILES) $(PYCFILES) $(GDIR)/__init__.py $(GDIR)/__init__.pyc
+
+
+$(PYDIR):
+	$(MKDIR) $@
+
+$(GDIR): | $(PYDIR)
+	$(MKDIR) $@
+
+$(DSTDIR): | $(GDIR)
+	$(MKDIR) $@
+
+$(DSTDIR)/%: % | $(DSTDIR)
+	$(INSTALL_DATA) $< $@
+
+#doxygen:
+DOXNAME = exceptions

+ 37 - 0
lib/python/exceptions/__init__.py

@@ -0,0 +1,37 @@
+# -*- coding: utf-8 -*-
+
+
+class DBError(Exception):
+    pass
+
+
+class FatalError(Exception):
+    pass
+
+
+class FlagError(Exception):
+    pass
+
+
+class GrassError(Exception):
+    pass
+
+
+class ImplementationError(Exception):
+    pass
+
+
+class OpenError(Exception):
+    pass
+
+
+class ParameterError(Exception):
+    pass
+
+
+class ScriptError(Exception):
+    pass
+
+
+class Usage(Exception):
+    pass

+ 3 - 27
lib/python/pygrass/errors.py

@@ -5,35 +5,11 @@ Created on Wed Aug 15 17:33:27 2012
 @author: pietro
 """
 from functools import wraps
-from grass.pygrass.messages import get_msgr
-
-
-class AbstractError(Exception):
-    def __init__(self, value):
-        self.value = value
-
-    def __str__(self):
-        return repr(self.value)
-
-
-class ParameterError(Exception):
-    pass
-
 
-class FlagError(Exception):
-    pass
+from grass.exceptions import (FlagError, ParameterError, DBError,
+                              GrassError, OpenError)
 
-
-class DBError(AbstractError):
-    pass
-
-
-class GrassError(AbstractError):
-    pass
-
-
-class OpenError(AbstractError):
-    pass
+from grass.pygrass.messages import get_msgr
 
 
 def must_be_open(method):

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

@@ -14,19 +14,10 @@ for details.
 @author Soeren Gebbert
 """
 import sys
-import grass.lib.gis as libgis
 from multiprocessing import Process, Lock, Pipe
 
-
-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
+import grass.lib.gis as libgis
+from grass.exceptions import FatalError
 
 
 def message_server(lock, conn):

+ 17 - 18
lib/python/pygrass/modules/interface/module.py

@@ -410,24 +410,20 @@ class Module(object):
             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
@@ -570,6 +566,9 @@ class Module(object):
             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
 
 ###############################################################################

+ 7 - 12
lib/python/script/core.py

@@ -33,6 +33,8 @@ import shutil
 import locale
 import codecs
 
+from grass.exceptions import ScriptError
+
 # i18N
 import gettext
 gettext.install('grasslibs', os.path.join(os.getenv("GISBASE"), 'locale'))
@@ -67,13 +69,6 @@ PIPE = subprocess.PIPE
 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()
 
 
@@ -519,7 +514,7 @@ def debug(msg, debug=1):
     if debug_level() >= debug:
         if sys.platform == "win32":
             msg = msg.replace('&', '^&')
-            
+
         run_command("g.message", flags='d', message=msg, debug=debug)
 
 def verbose(msg):
@@ -866,7 +861,7 @@ def _text_to_key_value_dict(filename, sep=":", val_sep=",", checkproj=False,
         @param val_sep The character that separates the values of a single key, default is ","
         @param checkproj True if it has to check some information about projection system
         @param checkproj True if it has to check some information about units
-        
+
         @return The dictionary
 
         A text file with this content:
@@ -985,9 +980,9 @@ def compare_key_value_text_files(filename_a, filename_b, sep=":",
 def diff_files(filename_a, filename_b):
     """!Diffs two text files and returns difference.
 
-    @param filename_a first file path    
+    @param filename_a first file path
     @param filename_b second file path
-    
+
     @return list of strings
     """
     import difflib
@@ -1619,7 +1614,7 @@ def create_location(dbase, location, epsg=None, proj4=None, filename=None,
         else:
             warning(_("Location <%s> already exists and will be overwritten") % location)
             shutil.rmtree(os.path.join(dbase, location))
-    
+
     kwargs = dict()
     if datum:
         kwargs['datum'] = datum

+ 1 - 9
lib/python/temporal/abstract_dataset.py

@@ -22,15 +22,7 @@ from metadata import *
 from temporal_topology_dataset_connector import *
 from spatial_topology_dataset_connector import *
 
-
-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)
+from grass.exceptions import ImplementationError
 
 ###############################################################################
 

+ 3 - 8
lib/python/temporal/temporal_algebra.py

@@ -396,6 +396,8 @@ from factory import *
 from open_stds import *
 import copy
 
+from grass.exceptions import FatalError
+
 ##############################################################################
 
 class TemporalAlgebraLexer(object):
@@ -650,17 +652,10 @@ class GlobalTemporalVar(object):
     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"""