Ejemplo n.º 1
0
    def __init__(self, message, parent=None, caption=None, showTraceback=True):
        """Show error message window

        :param message: error message
        :param parent: centre window on parent if given
        :param caption: window caption (if not given "Error")
        :param showTraceback: True to show also Python traceback
        """
        if not caption:
            caption = _('Error')
        style = wx.OK | wx.ICON_ERROR | wx.CENTRE
        exc_type, exc_value, exc_traceback = sys.exc_info()
        if exc_traceback:
            exception = traceback.format_exc()
            reason = exception.splitlines()[-1].split(':', 1)[-1].strip()

        if Debug.GetLevel() > 0 and exc_traceback:
            sys.stderr.write(exception)

        if showTraceback and exc_traceback:
            wx.MessageBox(parent=parent,
                          message=message + '\n\n%s: %s\n\n%s' %
                          (_('Reason'),
                           reason, exception),
                          caption=caption,
                          style=style)
        else:
            wx.MessageBox(parent=parent,
                          message=message,
                          caption=caption,
                          style=style)
Ejemplo n.º 2
0
 def __init__(self, message, parent=None):
     caption = _('Message')
     style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE
     wx.MessageBox(parent=parent,
                   message=message,
                   caption=caption,
                   style=style)
Ejemplo n.º 3
0
 def __init__(self, message, parent=None):
     caption = _('Warning')
     style = wx.OK | wx.ICON_WARNING | wx.CENTRE
     wx.MessageBox(parent=parent,
                   message=message,
                   caption=caption,
                   style=style)
Ejemplo n.º 4
0
def split(s):
    """Platform spefic shlex.split"""
    try:
        if sys.platform == "win32":
            return shlex.split(s.replace('\\', r'\\'))
        else:
            return shlex.split(s)
    except ValueError as e:
        sys.stderr.write(_("Syntax error: %s") % e)

    return []
Ejemplo n.º 5
0
    def __GetError(self):
        """Get error message or ''"""
        if not self.cmdThread.module:
            return _("Unable to exectute command: '%s'") % ' '.join(self.cmd)

        for type, msg in self.__ProcessStdErr():
            if type == 'ERROR':
                if _enc:
                    return unicode(msg, _enc)
                return msg

        return ''
Ejemplo n.º 6
0
def color_resolve(color):
    if len(color) > 0 and color[0] in "0123456789":
        rgb = tuple(map(int, color.split(':')))
        label = color
    else:
        # Convert color names to RGB
        try:
            rgb = str2rgb[color]
            label = color
        except KeyError:
            rgb = (200, 200, 200)
            label = _('Select Color')
    return (rgb, label)
Ejemplo n.º 7
0
def GetSettingsPath():
    """Get full path to the settings directory
    """
    try:
        verFd = open(os.path.join(ETCDIR, "VERSIONNUMBER"))
        version = int(verFd.readlines()[0].split(' ')[0].split('.')[0])
    except (IOError, ValueError, TypeError, IndexError) as e:
        sys.exit(
            _("ERROR: Unable to determine GRASS version. Details: %s") % e)

    verFd.close()

    # keep location of settings files rc and wx in sync with lib/init/grass.py
    if sys.platform == 'win32':
        return os.path.join(os.getenv('APPDATA'), 'GRASS%d' % version)

    return os.path.join(os.getenv('HOME'), '.grass%d' % version)
Ejemplo n.º 8
0
def ReadEpsgCodes(path):
    """Read EPSG code from the file

    :param path: full path to the file with EPSG codes

    Raise OpenError on failure.

    :return: dictionary of EPSG code
    """
    epsgCodeDict = dict()
    try:
        try:
            f = open(path, "r")
        except IOError:
            raise OpenError(_("failed to open '{0}'").format(path))

        code = None
        for line in f.readlines():
            line = line.strip()
            if len(line) < 1 or line.startswith('<metadata>'):
                continue

            if line[0] == '#':
                descr = line[1:].strip()
            elif line[0] == '<':
                code, params = line.split(" ", 1)
                try:
                    code = int(code.replace('<', '').replace('>', ''))
                except ValueError as e:
                    raise OpenError('{0}'.format(e))

            if code is not None:
                epsgCodeDict[code] = (descr, params)
                code = None

        f.close()
    except Exception as e:
        raise OpenError('{0}'.format(e))

    return epsgCodeDict
Ejemplo n.º 9
0
def GetVectorNumberOfLayers(vector):
    """Get list of all vector layers"""
    layers = list()
    if not vector:
        return layers

    fullname = grass.find_file(name=vector, element='vector')['fullname']
    if not fullname:
        Debug.msg(
            5, "utils.GetVectorNumberOfLayers(): vector map '%s' not found" %
            vector)
        return layers

    ret, out, msg = RunCommand('v.category',
                               getErrorMsg=True,
                               read=True,
                               input=fullname,
                               option='layers')
    if ret != 0:
        sys.stderr.write(
            _("Vector map <%(map)s>: %(msg)s\n") % {
                'map': fullname,
                'msg': msg
            })
        return layers
    else:
        Debug.msg(1, "GetVectorNumberOfLayers(): ret %s" % ret)

    for layer in out.splitlines():
        layers.append(layer)

    Debug.msg(
        3, "utils.GetVectorNumberOfLayers(): vector=%s -> %s" %
        (fullname, ','.join(layers)))

    return layers
Ejemplo n.º 10
0
def RunCommand(prog, flags="", overwrite=False, quiet=False,
               verbose=False, parent=None, read=False,
               parse=None, stdin=None, getErrorMsg=False, **kwargs):
    """Run GRASS command

    :param prog: program to run
    :param flags: flags given as a string
    :param overwrite, quiet, verbose: flags
    :param parent: parent window for error messages
    :param read: fetch stdout
    :param parse: fn to parse stdout (e.g. grass.parse_key_val) or None
    :param stdin: stdin or None
    :param getErrorMsg: get error messages on failure
    :param kwargs: program parameters

    :return: returncode (read == False and getErrorMsg == False)
    :return: returncode, messages (read == False and getErrorMsg == True)
    :return: stdout (read == True and getErrorMsg == False)
    :return: returncode, stdout, messages (read == True and getErrorMsg == True)
    :return: stdout, stderr
    """
    cmdString = b' '.join(grass.make_command(prog, flags, overwrite,
                                             quiet, verbose, **kwargs))

    Debug.msg(1, "gcmd.RunCommand(): %s" % cmdString)

    kwargs['stderr'] = subprocess.PIPE

    if read:
        kwargs['stdout'] = subprocess.PIPE

    if stdin:
        kwargs['stdin'] = subprocess.PIPE

    if parent:
        messageFormat = os.getenv('GRASS_MESSAGE_FORMAT', 'gui')
        os.environ['GRASS_MESSAGE_FORMAT'] = 'standard'

    start = time.time()

    ps = grass.start_command(prog, flags, overwrite, quiet, verbose, **kwargs)

    if stdin:
        ps.stdin.write(stdin)
        ps.stdin.close()
        ps.stdin = None

    stdout, stderr = list(map(DecodeString, ps.communicate()))

    if parent:  # restore previous settings
        os.environ['GRASS_MESSAGE_FORMAT'] = messageFormat

    ret = ps.returncode
    Debug.msg(1, "gcmd.RunCommand(): get return code %d (%.6f sec)" %
              (ret, (time.time() - start)))

    if ret != 0:
        if stderr:
            Debug.msg(2, "gcmd.RunCommand(): error %s" % stderr)
        else:
            Debug.msg(2, "gcmd.RunCommand(): nothing to print ???")

        if parent:
            GError(parent=parent,
                   caption=_("Error in %s") % prog,
                   message=stderr)

    if not read:
        if not getErrorMsg:
            return ret
        else:
            return ret, _formatMsg(stderr)

    if stdout:
        Debug.msg(3, "gcmd.RunCommand(): return stdout\n'%s'" % stdout)
    else:
        Debug.msg(3, "gcmd.RunCommand(): return stdout = None")

    if parse:
        stdout = parse(stdout)

    if not getErrorMsg:
        return stdout

    if read and getErrorMsg:
        return ret, stdout, _formatMsg(stderr)

    return stdout, _formatMsg(stderr)
Ejemplo n.º 11
0
    def __init__(self, cmd, stdin=None,
                 verbose=None, wait=True, rerr=False,
                 stdout=None, stderr=None):
        """
        :param cmd: command given as list
        :param stdin: standard input stream
        :param verbose: verbose level [0, 3] (--q, --v)
        :param wait: wait for child execution terminated
        :param rerr: error handling (when GException raised).
                     True for redirection to stderr, False for GUI
                     dialog, None for no operation (quiet mode)
        :param stdout:  redirect standard output or None
        :param stderr:  redirect standard error output or None
        """
        Debug.msg(1, "gcmd.Command(): %s" % ' '.join(cmd))
        self.cmd = cmd
        self.stderr = stderr

        #
        # set verbosity level
        #
        verbose_orig = None
        if ('--q' not in self.cmd and '--quiet' not in self.cmd) and \
                ('--v' not in self.cmd and '--verbose' not in self.cmd):
            if verbose is not None:
                if verbose == 0:
                    self.cmd.append('--quiet')
                elif verbose == 3:
                    self.cmd.append('--verbose')
                else:
                    verbose_orig = os.getenv("GRASS_VERBOSE")
                    os.environ["GRASS_VERBOSE"] = str(verbose)

        #
        # create command thread
        #
        self.cmdThread = CommandThread(cmd, stdin,
                                       stdout, stderr)
        self.cmdThread.start()

        if wait:
            self.cmdThread.join()
            if self.cmdThread.module:
                self.cmdThread.module.wait()
                self.returncode = self.cmdThread.module.returncode
            else:
                self.returncode = 1
        else:
            self.cmdThread.join(0.5)
            self.returncode = None

        if self.returncode is not None:
            Debug.msg(
                3, "Command(): cmd='%s', wait=%s, returncode=%d, alive=%s" %
                (' '.join(cmd), wait, self.returncode, self.cmdThread.isAlive()))
            if rerr is not None and self.returncode != 0:
                if rerr is False:  # GUI dialog
                    raise GException("%s '%s'%s%s%s %s%s" %
                                     (_("Execution failed:"),
                                      ' '.join(self.cmd),
                                      os.linesep, os.linesep,
                                      _("Details:"),
                                      os.linesep,
                                      _("Error: ") + self.__GetError()))
                elif rerr == sys.stderr:  # redirect message to sys
                    stderr.write("Execution failed: '%s'" %
                                 (' '.join(self.cmd)))
                    stderr.write(
                        "%sDetails:%s%s" %
                        (os.linesep,
                         _("Error: ") +
                            self.__GetError(),
                            os.linesep))
            else:
                pass  # nop
        else:
            Debug.msg(
                3, "Command(): cmd='%s', wait=%s, returncode=?, alive=%s" %
                (' '.join(cmd), wait, self.cmdThread.isAlive()))

        if verbose_orig:
            os.environ["GRASS_VERBOSE"] = verbose_orig
        elif "GRASS_VERBOSE" in os.environ:
            del os.environ["GRASS_VERBOSE"]
Ejemplo n.º 12
0
def StoreEnvVariable(key, value=None, envFile=None):
    """Store environmental variable

    If value is not given (is None) then environmental variable is
    unset.

    :param key: env key
    :param value: env value
    :param envFile: path to the environmental file (None for default location)
    """
    windows = sys.platform == 'win32'
    if not envFile:
        gVersion = grass.version()['version'].split('.', 1)[0]
        if not windows:
            envFile = os.path.join(os.getenv('HOME'), '.grass%s' % gVersion,
                                   'bashrc')
        else:
            envFile = os.path.join(os.getenv('APPDATA'), 'GRASS%s' % gVersion,
                                   'env.bat')

    # read env file
    environ = dict()
    lineSkipped = list()
    if os.path.exists(envFile):
        try:
            fd = open(envFile)
        except IOError as e:
            sys.stderr.write(_("Unable to open file '%s'\n") % envFile)
            return
        for line in fd.readlines():
            line = line.rstrip(os.linesep)
            try:
                k, v = map(lambda x: x.strip(),
                           line.split(' ', 1)[1].split('=', 1))
            except Exception as e:
                sys.stderr.write(
                    _("%s: line skipped - unable to parse '%s'\n"
                      "Reason: %s\n") % (envFile, line, e))
                lineSkipped.append(line)
                continue
            if k in environ:
                sys.stderr.write(_("Duplicated key: %s\n") % k)
            environ[k] = v

        fd.close()

    # update environmental variables
    if value is None:
        if key in environ:
            del environ[key]
    else:
        environ[key] = value

    # write update env file
    try:
        fd = open(envFile, 'w')
    except IOError as e:
        sys.stderr.write(_("Unable to create file '%s'\n") % envFile)
        return
    if windows:
        expCmd = 'set'
    else:
        expCmd = 'export'

    for key, value in six.iteritems(environ):
        fd.write('%s %s=%s\n' % (expCmd, key, value))

    # write also skipped lines
    for line in lineSkipped:
        fd.write(line + os.linesep)

    fd.close()