當前位置: 首頁>>代碼示例>>Python>>正文


Python gcmd.RunCommand類代碼示例

本文整理匯總了Python中core.gcmd.RunCommand的典型用法代碼示例。如果您正苦於以下問題:Python RunCommand類的具體用法?Python RunCommand怎麽用?Python RunCommand使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了RunCommand類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: ReprojectCoordinates

def ReprojectCoordinates(coord, projOut, projIn=None, flags=''):
    """Reproject coordinates

    :param coord: coordinates given as tuple
    :param projOut: output projection
    :param projIn: input projection (use location projection settings)

    :return: reprojected coordinates (returned as tuple)
    """
    coors = RunCommand('m.proj',
                       flags=flags,
                       input='-',
                       proj_in=projIn,
                       proj_out=projOut,
                       sep=';',
                       stdin='%f;%f' % (coord[0], coord[1]),
                       read=True)
    if coors:
        coors = coors.split(';')
        e = coors[0]
        n = coors[1]
        try:
            proj = projOut.split(' ')[0].split('=')[1]
        except IndexError:
            proj = ''
        if proj in ('ll', 'latlong', 'longlat') and 'd' not in flags:
            return (proj, (e, n))
        else:
            try:
                return (proj, (float(e), float(n)))
            except ValueError:
                return (None, None)

    return (None, None)
開發者ID:rkrug,項目名稱:grass-ci,代碼行數:34,代碼來源:utils.py

示例2: OnUninstall

 def OnUninstall(self, event):
     """Uninstall selected extensions"""
     eList = self._getSelectedExtensions()
     if not eList:
         return
     
     for ext in eList:
         files = RunCommand('g.extension', parent = self, read = True, quiet = True,
                            extension = ext, operation = 'remove').splitlines()
         if len(files) > 10:
             files = files[:10]
             files.append('...')
         dlg = wx.MessageDialog(parent = self,
                                message = _("List of files to be removed:\n%(files)s\n\n"
                                            "Do you want really to remove <%(ext)s> extension?") % \
                                    { 'files' : os.linesep.join(files), 'ext' : ext },
                                caption = _("Remove extension"),
                                style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
         
         if dlg.ShowModal() ==  wx.ID_YES:
             RunCommand('g.extension', flags = 'f', parent = self, quiet = True,
                        extension = ext, operation = 'remove')
     
     self.extList.LoadData()
     
     # update prompt
     globalvar.UpdateGRASSAddOnCommands(eList)
     toolboxesOutdated()
開發者ID:felipebetancur,項目名稱:grass-ci,代碼行數:28,代碼來源:extensions.py

示例3: OnConnect

    def OnConnect(self, event):
        """!Button 'Connect' pressed"""
        # 'r.in.wms -l' output changes depending on the parser used.
        # the parsing below depends on the cleaner `xml2` version.
        if not find_program('xml2'):
            GError(_("The 'xml2' parser is required, please install it "
                     "first. You may also try running r.in.wms directly "
                     "from the command line."))
            return

        server = self.server.GetValue()
        if not server:
            self.btn_import.Enable(False)
            return # not reachable

        layers = {}
        ret = RunCommand('r.in.wms',
                         quiet = True,
                         parent = self,
                         read = True,
                         flags = 'l',
                         mapserver = server)
        
        if not ret:
            self.list.LoadData()
            self.btn_import.Enable(False)
            return # no layers found
        
        lastLayer = lastStyle = ''
        for line in ret.splitlines():
            try:
                key, value = line.split(':', 1)
            except ValueError:
                continue
            key = key.strip().lower()
            value = value.strip()
            
            if key == 'layer':
                layers[value] = {}
                lastLayer = value
            elif key == 'title':
                if lastLayer and 'title' not in layers[lastLayer]:
                    layers[lastLayer][key] = value.decode('utf8')
            elif key == 'style':
                if lastLayer:
                    if 'style' not in layers[lastLayer]:
                        layers[lastLayer]['style'] = {}
                    layers[lastLayer]['style'][value] = ''
                    lastStyle = value
            elif key == 'style title':
                if lastLayer:
                    layers[lastLayer]['style'][lastStyle] = value

        # update list of layers
        self.list.LoadData(layers)
        
        if len(layers.keys()) > 0:
            self.btn_import.Enable(True)
        else:
            self.btn_import.Enable(False)
開發者ID:imincik,項目名稱:pkg-grass,代碼行數:60,代碼來源:ogc_services.py

示例4: _projInfo

    def _projInfo(self):
        """Return region projection and map units information
        """
        projinfo = dict()
        if not grass.find_program('g.proj', '--help'):
            sys.exit(_("GRASS module '%s' not found. Unable to start map "
                       "display window.") % 'g.proj')
        env = os.environ.copy()
        if self.gisrc:
            env['GISRC'] = self.gisrc
        ret = RunCommand(prog='g.proj', read=True, flags='p', env=env)

        if not ret:
            return projinfo

        for line in ret.splitlines():
            if ':' in line:
                key, val = map(lambda x: x.strip(), line.split(':'))
                if key in ['units']:
                    val = val.lower()
                projinfo[key] = val
            elif "XY location (unprojected)" in line:
                projinfo['proj'] = 'xy'
                projinfo['units'] = ''
                break

        return projinfo
開發者ID:imincik,項目名稱:pkg-grass7,代碼行數:27,代碼來源:render.py

示例5: GetTempfile

def GetTempfile(pref=None):
    """Creates GRASS temporary file using defined prefix.

    .. todo::
        Fix path on MS Windows/MSYS

    :param pref: prefer the given path

    :return: Path to file name (string) or None
    """
    ret = RunCommand('g.tempfile',
                     read=True,
                     pid=os.getpid())

    tempfile = ret.splitlines()[0].strip()

    # FIXME
    # ugly hack for MSYS (MS Windows)
    if platform.system() == 'Windows':
        tempfile = tempfile.replace("/", "\\")
    try:
        path, file = os.path.split(tempfile)
        if pref:
            return os.path.join(pref, file)
        else:
            return tempfile
    except:
        return None
開發者ID:rkrug,項目名稱:grass-ci,代碼行數:28,代碼來源:utils.py

示例6: _getCategories

    def _getCategories(self, coords, qdist):
        """Get layer/category pairs for all available
        layers

        :return: True line found or False if not found
        """
        ret = RunCommand('v.what',
                         parent = self,
                         quiet = True,
                         map = self.vectorName,
                         east_north = '%f,%f' % \
                             (float(coords[0]), float(coords[1])),
                         distance = qdist)

        if not ret:
            return False

        for item in ret.splitlines():
            litem = item.lower()
            if "id:" in litem: # get line id
                self.line = int(item.split(':')[1].strip())
            elif "layer:" in litem: # add layer
                layer = int(item.split(':')[1].strip())
                if layer not in self.cats.keys():
                    self.cats[layer] = []
            elif "category:" in litem: # add category
                self.cats[layer].append(int(item.split(':')[1].strip()))

        return True
開發者ID:caomw,項目名稱:grass,代碼行數:29,代碼來源:dialogs.py

示例7: GetListOfMapsets

def GetListOfMapsets(dbase, location, selectable=False):
    """Get list of mapsets in given GRASS location

    :param dbase: GRASS database path
    :param location: GRASS location
    :param selectable: True to get list of selectable mapsets, otherwise all

    :return: list of mapsets - sorted (PERMANENT first)
    """
    listOfMapsets = list()

    if selectable:
        ret = RunCommand('g.mapset',
                         read=True,
                         flags='l',
                         location=location,
                         dbase=dbase)

        if not ret:
            return listOfMapsets

        for line in ret.rstrip().splitlines():
            listOfMapsets += line.split(' ')
    else:
        for mapset in glob.glob(os.path.join(dbase, location, "*")):
            if os.path.isdir(mapset) and os.path.isfile(
                    os.path.join(dbase, location, mapset, "WIND")):
                listOfMapsets.append(os.path.basename(mapset))

    ListSortLower(listOfMapsets)
    return listOfMapsets
開發者ID:rkrug,項目名稱:grass-ci,代碼行數:31,代碼來源:utils.py

示例8: OnRun

    def OnRun(self, event):
        """Import/Link data (each layes as separate vector map)"""
        self.commandId = -1
        data = self.list.GetLayers()

        data = self._getLayersToReprojetion(2, 3)

        if data is None:
            return

        if not data:
            GMessage(_("No layers selected. Operation canceled."),
                     parent=self)
            return

        dsn = self.dsnInput.GetDsn()
        ext = self.dsnInput.GetFormatExt()

        for layer, output, listId in data:
            userData = {}

            if self.dsnInput.GetType() == 'dir':
                idsn = os.path.join(dsn, layer)
            else:
                idsn = dsn

            # check number of bands
            nBandsStr = RunCommand('r.in.gdal',
                                   flags='p',
                                   input=idsn, read=True)
            nBands = -1
            if nBandsStr:
                try:
                    nBands = int(nBandsStr.rstrip('\n'))
                except:
                    pass
            if nBands < 0:
                GWarning(_("Unable to determine number of raster bands"),
                         parent=self)
            nBands = 1

            userData['nbands'] = nBands
            cmd = self.getSettingsPageCmd()
            cmd.append('input=%s' % dsn)
            cmd.append('output=%s' % output)

            if self.overwrite.IsChecked():
                cmd.append('--overwrite')

            if UserSettings.Get(group='cmd', key='overwrite',
                                subkey='enabled') and '--overwrite' not in cmd:
                cmd.append('--overwrite')

            # run in Layer Manager
            self._giface.RunCmd(
                cmd,
                onDone=self.OnCmdDone,
                userData=userData,
                addLayer=False)
開發者ID:rkrug,項目名稱:grass-ci,代碼行數:59,代碼來源:import_export.py

示例9: GetColorTables

def GetColorTables():
    """Get list of color tables"""
    ret = RunCommand('r.colors',
                     read=True,
                     flags='l')
    if not ret:
        return list()

    return ret.splitlines()
開發者ID:rkrug,項目名稱:grass-ci,代碼行數:9,代碼來源:utils.py

示例10: GroupSet

    def GroupSet(self, group, subgroup):
        kwargs = {}
        if subgroup:
            kwargs['subgroup'] = subgroup

        res = RunCommand('i.group',
                         flags='g',
                         group=group,
                         read=True, **kwargs).strip()

        if res.splitlines()[0]:
            bands = res.splitlines()
            self.scatt_mgr.SetBands(bands)
開發者ID:rkrug,項目名稱:grass-ci,代碼行數:13,代碼來源:controllers.py

示例11: CreateDatalist

    def CreateDatalist(self, rpair):
        """Build a list of cell value, frequency pairs for histogram
            frequency can be in cell counts, percents, or area
        """
        datalist = []

        if self.scattertype == "bubble":
            freqflag = "cn"
        else:
            freqflag = "n"

        try:
            ret = RunCommand(
                "r.stats",
                parent=self,
                input="%s,%s" % rpair,
                flags=freqflag,
                nsteps=self.bins,
                sep=",",
                quiet=True,
                read=True,
            )

            if not ret:
                return datalist

            for line in ret.splitlines():
                rast1, rast2 = line.strip().split(",")
                rast1 = rast1.strip()
                if "-" in rast1:
                    if rast1[0] == "-":
                        rast1 = "-" + rast1.split("-")[1]
                    else:
                        rast1 = rast1.split("-")[0]

                rast2 = rast2.strip()
                if "-" in rast2:
                    if rast2[0] == "-":
                        rast2 = "-" + rast2.split("-")[1]
                    else:
                        rast2 = rast2.split("-")[0]

                rast1 = rast1.encode("ascii", "ignore")
                rast2 = rast2.encode("ascii", "ignore")

                datalist.append((rast1, rast2))

            return datalist
        except GException as e:
            GError(parent=self, message=e.value)
            return None
開發者ID:rkrug,項目名稱:grass-ci,代碼行數:51,代碼來源:scatter.py

示例12: CreateDatalist

    def CreateDatalist(self, rpair):
        """Build a list of cell value, frequency pairs for histogram
            frequency can be in cell counts, percents, or area
        """
        datalist = []
        
        if self.scattertype == 'bubble': 
            freqflag = 'cn'
        else:
            freqflag = 'n'
                
        try:
            ret = RunCommand("r.stats",
                             parent = self,
                             input = '%s,%s' % rpair,
                             flags = freqflag,
                             nsteps = self.bins,
                             sep = ',',
                             quiet = True,
                             read = True)
            
            if not ret:
                return datalist
            
            for line in ret.splitlines():
                rast1, rast2 = line.strip().split(',')
                rast1 = rast1.strip()
                if '-' in rast1:
                    if rast1[0] == '-':
                        rast1 = '-' + rast1.split('-')[1]
                    else:
                        rast1 = rast1.split('-')[0]

                rast2 = rast2.strip()
                if '-' in rast2:
                    if rast2[0] == '-':
                        rast2 = '-' + rast2.split('-')[1]
                    else:
                        rast2 = rast2.split('-')[0]
                
                rast1 = rast1.encode('ascii', 'ignore')
                rast2 = rast2.encode('ascii', 'ignore')
                    
                datalist.append((rast1,rast2))

            return datalist
        except GException as e:
            GError(parent = self,
                   message = e.value)
            return None
開發者ID:felipebetancur,項目名稱:grass-ci,代碼行數:50,代碼來源:scatter.py

示例13: GetGroupBands

    def GetGroupBands(self, group, subgroup):
        """Get list of raster bands which are in the soubgroup of group with both having same name."""

        kwargs = {}
        if subgroup:
            kwargs['subgroup'] = subgroup

        res = RunCommand('i.group',
                         flags='g',
                         group=group,
                         read = True, **kwargs).strip()
        bands = None
        if res.split('\n')[0]:
            bands = res.split('\n')
            
        return bands
開發者ID:caomw,項目名稱:grass,代碼行數:16,代碼來源:dialogs.py

示例14: CreateDatalist

    def CreateDatalist(self, raster):
        """Build a list of cell value, frequency pairs for histogram
            frequency can be in cell counts, percents, or area
        """
        datalist = []

        if self.histtype == 'count':
            freqflag = 'cn'
        if self.histtype == 'percent':
            freqflag = 'pn'
        if self.histtype == 'area':
            freqflag = 'an'

        try:
            ret = RunCommand("r.stats",
                             parent=self,
                             input=raster,
                             flags=freqflag,
                             nsteps=self.bins,
                             sep=',',
                             quiet=True,
                             read=True)

            if not ret:
                return datalist

            for line in ret.splitlines():
                cellval, histval = line.strip().split(',')
                histval = histval.strip()
                if self.raster[raster]['datatype'] != 'CELL':
                    if cellval[0] == '-':
                        cellval = '-' + cellval.split('-')[1]
                    else:
                        cellval = cellval.split('-')[0]

                if self.histtype == 'percent':
                    histval = histval.rstrip('%')

                datalist.append((cellval, histval))

            return datalist
        except GException as e:
            GError(parent=self,
                   message=e.value)
            return None
開發者ID:GRASS-GIS,項目名稱:grass-ci,代碼行數:45,代碼來源:histogram.py

示例15: UpdateMapsets

 def UpdateMapsets(self, location):
     """Update list of mapsets"""
     self.FormerMapsetSelection = wx.NOT_FOUND # for non-selectable item
     
     self.listOfMapsetsSelectable = list()
     self.listOfMapsets = GetListOfMapsets(self.gisdbase, location)
     
     self.lbmapsets.Clear()
     
     # disable mapset with denied permission
     locationName = os.path.basename(location)
     
     ret = RunCommand('g.mapset',
                      read = True,
                      flags = 'l',
                      location = locationName,
                      gisdbase = self.gisdbase)
         
     if ret:
         for line in ret.splitlines():
             self.listOfMapsetsSelectable += line.split(' ')
     else:
         RunCommand("g.gisenv",
                    set = "GISDBASE=%s" % self.gisdbase)
         RunCommand("g.gisenv",
                    set = "LOCATION_NAME=%s" % locationName)
         RunCommand("g.gisenv",
                    set = "MAPSET=PERMANENT")
         # first run only
         self.listOfMapsetsSelectable = copy.copy(self.listOfMapsets)
     
     disabled = []
     idx = 0
     for mapset in self.listOfMapsets:
         if mapset not in self.listOfMapsetsSelectable or \
                 os.path.isfile(os.path.join(self.gisdbase,
                                             locationName,
                                             mapset, ".gislock")):
             disabled.append(idx)
         idx +=  1
     
     self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled = disabled)
     
     return self.listOfMapsets
開發者ID:felipebetancur,項目名稱:grass-ci,代碼行數:44,代碼來源:gis_set.py


注:本文中的core.gcmd.RunCommand類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。