[GRASS-SVN] r35738 - in grass/trunk/gui/wxpython: . gui_modules

svn_grass at osgeo.org svn_grass at osgeo.org
Mon Feb 2 16:12:55 EST 2009


Author: martinl
Date: 2009-02-02 16:12:54 -0500 (Mon, 02 Feb 2009)
New Revision: 35738

Modified:
   grass/trunk/gui/wxpython/gis_set.py
   grass/trunk/gui/wxpython/gui_modules/dbm.py
   grass/trunk/gui/wxpython/gui_modules/gcmd.py
   grass/trunk/gui/wxpython/gui_modules/gdialogs.py
   grass/trunk/gui/wxpython/gui_modules/georect.py
   grass/trunk/gui/wxpython/gui_modules/goutput.py
   grass/trunk/gui/wxpython/gui_modules/location_wizard.py
   grass/trunk/gui/wxpython/gui_modules/mapdisp.py
   grass/trunk/gui/wxpython/gui_modules/mcalc_builder.py
   grass/trunk/gui/wxpython/gui_modules/render.py
   grass/trunk/gui/wxpython/gui_modules/toolbars.py
   grass/trunk/gui/wxpython/gui_modules/utils.py
   grass/trunk/gui/wxpython/wxgui.py
Log:
wxGUI: eliminate gcmd.Command() usage (step 2)


Modified: grass/trunk/gui/wxpython/gis_set.py
===================================================================
--- grass/trunk/gui/wxpython/gis_set.py	2009-02-02 19:28:57 UTC (rev 35737)
+++ grass/trunk/gui/wxpython/gis_set.py	2009-02-02 21:12:54 UTC (rev 35738)
@@ -75,8 +75,6 @@
 
         # labels
         ### crashes when LOCATION doesn't exist
-        # versionCmd = gcmd.Command(['g.version'], log=None)
-        # grassVersion = versionCmd.ReadStdOutput()[0].replace('GRASS', '').strip()
         versionFile = open(os.path.join(globalvar.ETCDIR, "VERSIONNUMBER"))
         grassVersion = versionFile.readline().replace('%s' % os.linesep, '').strip()
         versionFile.close()
@@ -565,21 +563,24 @@
         locationName = os.path.basename(location)
 
         try:
-            mapsets = gcmd.Command(['g.mapset',
-                                    '-l',
-                                    'location=%s' % locationName,
-                                    'gisdbase=%s' % self.gisdbase],
-                                   stderr=None)
+            ret = gcmd.RunCommand('g.mapset',
+                                  read = True
+                                  flags = '-l',
+                                  location = locationName,
+                                  gisdbase = self.gisdbase)
             
-            for line in mapsets.ReadStdOutput():
+            if not ret:
+                raise gcmd.CmdError("")
+            
+            for line in ret.splitlines():
                 self.listOfMapsetsSelectable += line.split(' ')
-        except gcmd.CmdError:
-            gcmd.Command(["g.gisenv",
-                          "set=GISDBASE=%s" % self.gisdbase])
-            gcmd.Command(["g.gisenv",
-                          "set=LOCATION_NAME=%s" % locationName])
-            gcmd.Command(["g.gisenv",
-                          "set=MAPSET=PERMANENT"])
+        except:
+            gcmd.RunCommand("g.gisenv",
+                            set= "GISDBASE=%s" % self.gisdbase)
+            gcmd.RunCommand("g.gisenv",
+                            set = "LOCATION_NAME=%s" % locationName)
+            gcmd.RunCommand("g.gisenv",
+                            set = "MAPSET=PERMANENT")
             # first run only
             self.listOfMapsetsSelectable = copy.copy(self.listOfMapsets)
         
@@ -681,13 +682,16 @@
 
     def OnStart(self, event):
         """'Start GRASS' button clicked"""
-        gcmd.Command(["g.gisenv",
-                      "set=GISDBASE=%s" % self.tgisdbase.GetValue()])
-        gcmd.Command(["g.gisenv",
-                      "set=LOCATION_NAME=%s" % self.listOfLocations[self.lblocations.GetSelection()]])
-        gcmd.Command(["g.gisenv",
-                      "set=MAPSET=%s" % self.listOfMapsets[self.lbmapsets.GetSelection()]])
-
+        gcmd.RunCommand("g.gisenv",
+                        set = "GISDBASE=%s" % \
+                            self.tgisdbase.GetValue())
+        gcmd.RunCommand("g.gisenv",
+                        set = "LOCATION_NAME=%s" % \
+                            self.listOfLocations[self.lblocations.GetSelection()])
+        gcmd.RunCommand("g.gisenv",
+                        set = "MAPSET=%s" % \
+                            self.listOfMapsets[self.lbmapsets.GetSelection()])
+        
         self.Destroy()
         sys.exit(0)
 

Modified: grass/trunk/gui/wxpython/gui_modules/dbm.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/dbm.py	2009-02-02 19:28:57 UTC (rev 35737)
+++ grass/trunk/gui/wxpython/gui_modules/dbm.py	2009-02-02 21:12:54 UTC (rev 35738)
@@ -167,16 +167,10 @@
                                           "'Manage layers' tab.") % tableName,
                                 parent=self.parent)
         
-        cmd = ["v.db.select",
-               "-c", "--q",
-               "map=%s" % self.mapDBInfo.map,
-               "layer=%d" % layer]
-               
         if not columns:
             columns = self.mapDBInfo.GetColumns(tableName)
         else:
             all = self.mapDBInfo.GetColumns(tableName)
-            cmd.append("columns=%s" % ','.join(columns))
             for col in columns:
                 if col not in all:
                     wx.MessageBox(parent=self,
@@ -185,10 +179,6 @@
                                       { 'column' : col, 'table' : tableName },
                                   caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
                     return
-
-
-        if where:
-            cmd.append("where=%s" % where)
         
         try:
             # for maps connected via v.external
@@ -205,9 +195,24 @@
         # TODO: more effective way should be implemented...
         outFile = tempfile.NamedTemporaryFile(mode='w+b')
         
-        selectCommand = gcmd.Command(cmd,
-                                     stdout=outFile)
-
+        if columns:
+            ret = gcmd.RunCommand('v.db.select',
+                                  quiet = True,
+                                  flags = 'c',
+                                  map = self.mapDBInfo.map,
+                                  layer = layer,
+                                  columns = ','.join(columns),
+                                  where = where,
+                                  stdout=outFile)
+        else:
+           ret = gcmd.RunCommand('v.db.select',
+                                 quiet = True,
+                                 flags = 'c',
+                                 map = self.mapDBInfo.map,
+                                 layer = layer,
+                                 where = where,
+                                 stdout=outFile) 
+        
         # These two should probably be passed to init more cleanly
         # setting the numbers of items = number of elements in the dictionary
         self.itemDataMap  = {}
@@ -1465,10 +1470,11 @@
                 else:
                     list.SetItemText(item, nameTo)
 
-                    self.listOfCommands.append(['v.db.renamecol',
-                                                'map=%s' % self.vectorName,
-                                                'layer=%d' % self.layer,
-                                                'column=%s,%s' % (name, nameTo)])
+                    self.listOfCommands.append(('v.db.renamecol',
+                                                { 'map'    : self.vectorName,
+                                                  'layer'  : self.layer,
+                                                  'column' : '%s,%s' % (name, nameTo) }
+                                                ))
             else:
                 wx.MessageBox(parent=self,
                               message=_("Unable to rename column. "
@@ -1515,10 +1521,11 @@
 
         item = list.GetFirstSelected()
         while item != -1:
-            self.listOfCommands.append(['v.db.dropcol',
-                                        'map=%s' % self.vectorName,
-                                        'layer=%d' % self.layer,
-                                        'column=%s' % list.GetItemText(item)])
+            self.listOfCommands.append(('v.db.dropcol',
+                                        { 'map' : self.vectorName,
+                                          'layer' : self.layer,
+                                          'column' : list.GetItemText(item) }
+                                        ))
             list.DeleteItem(item)
             item = list.GetFirstSelected()
 
@@ -1537,10 +1544,11 @@
         table = self.mapDBInfo.layers[self.layer]['table']
         cols = self.mapDBInfo.GetColumns(table)
         for col in cols:
-            self.listOfCommands = [['v.db.dropcol',
-                                    'map=%s' % self.vectorName,
-                                    'layer=%d' % self.layer,
-                                    'column=%s' % col]]
+            self.listOfCommands.append(('v.db.dropcol',
+                                        { 'map' : self.vectorName,
+                                          'layer' : self.layer,
+                                          'column' : col }
+                                        ))
         self.FindWindowById(self.layerPage[self.layer]['tableData']).DeleteAllItems()
 
         # apply changes
@@ -1599,11 +1607,11 @@
         # add v.db.addcol command to the list
         if type == 'varchar':
             type += ' (%d)' % length
-        self.listOfCommands.append(['v.db.addcol',
-                                    'map=%s' % self.vectorName,
-                                    'layer=%d' % self.layer,
-                                    'columns=%s %s' % (name, type)])
-
+        self.listOfCommands.append(('v.db.addcol',
+                                    { 'map' : self.vectorName,
+                                      'layer' : self.layer,
+                                      'columns' : (name, type) }
+                                    ))
         # apply changes
         self.ApplyCommands()
         
@@ -1677,10 +1685,11 @@
         # perform GRASS commands (e.g. v.db.addcol)
         if len(self.listOfCommands) > 0:
             for cmd in self.listOfCommands:
-                Debug.msg(3, 'AttributeManager.ApplyCommands() cmd=\'%s\'' %
-                          ' '.join(cmd))
-                gcmd.Command(cmd)
-
+                gcmd.RunCommand(prog = cmd[0],
+                                quiet = True,
+                                parent = self,
+                                **cmd[1])
+            
             self.mapDBInfo = VectorDBInfo(self.vectorName)
             table = self.mapDBInfo.layers[self.layer]['table']
 
@@ -1912,12 +1921,12 @@
             return
         else:
             # dialog to get file name
-            gdialogs.CreateNewVector(parent=self, title=_('Extract selected features'),
-                                     log=self.cmdLog,
-                                     cmdDef=(["v.extract",
-                                              "input=%s" % self.vectorName,
-                                              "list=%s" % utils.ListOfCatsToRange(cats)],
-                                             "output"))
+            gdialogs.CreateNewVector(parent = self, title = _('Extract selected features'),
+                                     log = self.cmdLog,
+                                     cmd = (('v.extract',
+                                             { 'input' : self.vectorName,
+                                               'list' : utils.ListOfCatsToRange(cats) },
+                                             'output')))
     def OnDeleteSelected(self, event):
         """
         Delete vector objects selected in attribute browse window

Modified: grass/trunk/gui/wxpython/gui_modules/gcmd.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/gcmd.py	2009-02-02 19:28:57 UTC (rev 35737)
+++ grass/trunk/gui/wxpython/gui_modules/gcmd.py	2009-02-02 21:12:54 UTC (rev 35738)
@@ -621,4 +621,3 @@
         return ret
 
     return stdout
-

Modified: grass/trunk/gui/wxpython/gui_modules/gdialogs.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/gdialogs.py	2009-02-02 19:28:57 UTC (rev 35737)
+++ grass/trunk/gui/wxpython/gui_modules/gdialogs.py	2009-02-02 21:12:54 UTC (rev 35738)
@@ -124,16 +124,15 @@
 
         return mapName
     
-def CreateNewVector(parent, cmdDef, title=_('Create new vector map'),
+def CreateNewVector(parent, cmd, title=_('Create new vector map'),
                     exceptMap=None, log=None, disableAdd=False):
     """Create new vector map layer
 
-    @cmdList tuple/list (cmd list, output paramater)
+    @cmd cmd (prog, **kwargs)
     
     @return tuple (name of create vector map, add to layer tree)
     @return None of failure
     """
-    cmd = cmdDef[0]
     dlg = NewVectorDialog(parent, wx.ID_ANY, title,
                           disableAdd)
     if dlg.ShowModal() == wx.ID_OK:
@@ -148,13 +147,14 @@
         if outmap == '': # should not happen
             return False
         
-        cmd.append("%s=%s" % (cmdDef[1], outmap))
+        cmd[1][cmd[2]] = outmap
         
         try:
             listOfVectors = grass.list_grouped('vect')[grass.gisenv()['MAPSET']]
         except KeyError:
             listOfVectors = []
         
+        overwrite = False
         if not UserSettings.Get(group='cmd', key='overwrite', subkey='enabled') and \
                 outmap in listOfVectors:
             dlgOw = wx.MessageDialog(parent, message=_("Vector map <%s> already exists "
@@ -163,18 +163,21 @@
                                      caption=_("Overwrite?"),
                                      style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
             if dlgOw.ShowModal() == wx.ID_YES:
-                cmd.append('--overwrite')
+                overwrite = True
             else:
                 dlgOw.Destroy()
                 return False
 
         if UserSettings.Get(group='cmd', key='overwrite', subkey='enabled') is True:
-            cmd.append('--overwrite')
+            overwrite = True
         
         try:
-            gcmd.Command(cmd)
+            print cmd
+            gcmd.RunCommand(prog = cmd[0],
+                            overwrite = overwrite,
+                            **cmd[1])
         except gcmd.CmdError, e:
-            print >> sys.stderr, e
+            e.Show()
             return None
 
         #

Modified: grass/trunk/gui/wxpython/gui_modules/georect.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/georect.py	2009-02-02 19:28:57 UTC (rev 35737)
+++ grass/trunk/gui/wxpython/gui_modules/georect.py	2009-02-02 21:12:54 UTC (rev 35738)
@@ -509,8 +509,8 @@
         """Process i.group"""
         # update the page
         if dcmd:
-            gcmd.Command(dcmd, stderr=None)
-
+            gcmd.RunCommand(utils.CmdToTuple(dcmd))
+        
         self.OnEnterPage()
         self.Update()
         

Modified: grass/trunk/gui/wxpython/gui_modules/goutput.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/goutput.py	2009-02-02 19:28:57 UTC (rev 35737)
+++ grass/trunk/gui/wxpython/gui_modules/goutput.py	2009-02-02 21:12:54 UTC (rev 35738)
@@ -370,9 +370,9 @@
 
             # if command is not a GRASS command, treat it like a shell command
             try:
-                generalCmd = gcmd.Command(cmdlist,
-                                          stdout=self.cmd_stdout,
-                                          stderr=self.cmd_stderr)
+                gcmd.Command(cmdlist,
+                             stdout=self.cmd_stdout,
+                             stderr=self.cmd_stderr)
             except gcmd.CmdError, e:
                 print >> sys.stderr, e
 

Modified: grass/trunk/gui/wxpython/gui_modules/location_wizard.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/location_wizard.py	2009-02-02 19:28:57 UTC (rev 35737)
+++ grass/trunk/gui/wxpython/gui_modules/location_wizard.py	2009-02-02 21:12:54 UTC (rev 35738)
@@ -2217,8 +2217,6 @@
             self.currlocation = envval['LOCATION_NAME'].strip("';")
             self.currmapset = envval['MAPSET'].strip("';")
             if self.currlocation != self.location or self.currmapset != 'PERMANENT':
-                # cmdlist = ['g.mapset', 'location=%s' % self.location, 'mapset=PERMANENT']
-                # gcmd.Command(cmdlist
                 gcmd.RunCommand('g.gisenv',
                                 set = 'LOCATION_NAME=%s' % self.location)
                 gcmd.RunCommand('g.gisenv',

Modified: grass/trunk/gui/wxpython/gui_modules/mapdisp.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/mapdisp.py	2009-02-02 19:28:57 UTC (rev 35737)
+++ grass/trunk/gui/wxpython/gui_modules/mapdisp.py	2009-02-02 21:12:54 UTC (rev 35738)
@@ -1101,8 +1101,8 @@
         mapname = None
         raststr = ''
         vectstr = ''
-        rcmd = []
-        vcmd = []
+        rcmd = ['r.what', { 'quiet' : True }]
+        vcmd = ['v.what', { 'quiet' : True }]
         for layer in self.tree.GetSelections():
             type = self.tree.GetPyData(layer)[0]['maplayer'].type
             dcmd = self.tree.GetPyData(layer)[0]['cmd']
@@ -1120,11 +1120,10 @@
         
         # build query commands for any selected rasters and vectors
         if raststr != '':
-            rcmd = ['r.what', '--q',
-                    '-f',
-                    'input=%s' % raststr.rstrip(','),
-                    'east_north=%f,%f' % (float(east), float(north))]
-
+            rcmd[1]['flags'] = 'f'
+            rcmd[1]['input'] = raststr.rstrip(',')
+            rcmd[1]['east_north'] = '%f,%f' % (float(east), float(north))
+        
         if vectstr != '':
             # check for vector maps open to be edited
             digitToolbar = self.toolbars['vdigit']
@@ -1143,23 +1142,25 @@
                 self.gismanager.goutput.WriteCmdLog("Nothing to query.")
                 return
             
-            vcmd = ['v.what', '--q',
-                    '-a',
-                    'map=%s' % vectstr.rstrip(','),
-                    'east_north=%f,%f' % (float(east), float(north)),
-                    'distance=%f' % qdist]
-
+            vcmd[1]['flags'] = 'a'
+            vcmd[1]['map'] = vectstr.rstrip(',')
+            vcmd[1]['east_north'] = '%f,%f' % (float(east), float(north)),
+            vcmd[1]['distance'] = qdist
+        
         # parse query command(s)
         if self.gismanager:
             if rcmd:
-                self.gismanager.goutput.RunCmd(rcmd, compReg=False)
+                self.gismanager.goutput.RunCmd(prog = rcmd[0],
+                                               compReg=False,
+                                               **rcmd[1])
             if vcmd:
-                self.gismanager.goutput.RunCmd(vcmd)
+                self.gismanager.goutput.RunCmd(prog = vcmd[0],
+                                               **vcmd)
         else:
             if rcmd:
-                gcmd.Command(rcmd) # TODO: -> grass.run_command
+                gcmd.RunCommand(rcmd)
             if vcmd:
-                gcmd.Command(vcmd) # TODO: -> grass.run_command
+                gcmd.RunCommand(vcmd)
 
         # restore GRASS_REGION
         if tmpreg:

Modified: grass/trunk/gui/wxpython/gui_modules/mcalc_builder.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/mcalc_builder.py	2009-02-02 19:28:57 UTC (rev 35737)
+++ grass/trunk/gui/wxpython/gui_modules/mcalc_builder.py	2009-02-02 21:12:54 UTC (rev 35738)
@@ -387,20 +387,15 @@
             wx.MessageBox("You must enter a mapcalc statement to create a new map")
             return
 
-        try:
-            mctxt = self.text_mcalc.GetValue().strip().replace("\n"," ")
-            mctxt = mctxt.replace(" ","")
-            if self.dimension == 3:
-                cmdlist = ["r3.mapcalc"," %s=%s" % (self.newmap,mctxt)]
-            else:
-                cmdlist = ["r.mapcalc"," %s=%s" % (self.newmap,mctxt)]
-
-            p = gcmd.Command(cmdlist)
-            if p.returncode == 0:
-                wx.MessageBox("Map %s created successfully" % self.newmap)
-        except:
-            pass
-
+        mctxt = self.text_mcalc.GetValue().strip().replace("\n"," ")
+        mctxt = mctxt.replace(" ","")
+        if self.dimension == 3:
+            gcmd.RunCommand('r3.mapcalc',
+                            expression = "%s=%s" % (self.newmap,mctxt))
+        else:
+            gcmd.RunCommand('r.mapcalc',
+                            expression = "%s=%s" % (self.newmap,mctxt))
+        
     def OnClear(self, event):
         """
         Clears text area

Modified: grass/trunk/gui/wxpython/gui_modules/render.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/render.py	2009-02-02 19:28:57 UTC (rev 35737)
+++ grass/trunk/gui/wxpython/gui_modules/render.py	2009-02-02 21:12:54 UTC (rev 35738)
@@ -72,9 +72,9 @@
         @param hidden layer is hidden, won't be listed in Layer Manager if True
         @param opacity layer opacity <0;1>
         """
-        self.type    = type
-        self.name    = name
-        self.cmdlist = cmd
+        self.type = type
+        self.name = name
+        self.cmd  = utils.CmdToTuple(cmd)
 
         self.active  = active
         self.hidden  = hidden
@@ -105,7 +105,7 @@
         @return rendered image filename
         @return None on error
         """
-        if len(self.cmdlist) == 0:
+        if not self.cmd:
             return None
         
         # ignore in 2D
@@ -140,20 +140,22 @@
         try:
             if self.type == 'command':
                 read = False
-                for cmd in self.cmdlist:
-                    runcmd = gcmd.Command(cmd=cmd + ['--q'],
-                                          stderr=None)
-                    if runcmd.returncode != 0:
+                for cmd in self.cmd:
+                    ret = gcmd.RunCommand(self.cmd[0],
+                                          quiet = True,
+                                          **self.cmd[1])
+                    if ret.returncode != 0:
                         break
                     if not read:
                         os.environ["GRASS_PNG_READ"] = "TRUE"
                 
                 os.environ["GRASS_PNG_READ"] = "FALSE"
             else:
-                runcmd = gcmd.Command(cmd=self.cmdlist + ['--q'],
-                                      stderr=None)
-            
-            if runcmd.returncode != 0:
+                ret = gcmd.RunCommand(self.cmd[0],
+                                      quiet = True,
+                                      **self.cmd[1])
+                
+            if ret != 0:
                 #clean up after probley
                 try:
                     os.remove(self.mapfile)
@@ -196,14 +198,14 @@
         """
         if string:
             if self.type == 'command':
-                cmdStr = ''
-                for cmd in self.cmdlist:
-                    cmdStr += ' '.join(cmd) + ';'
-                return cmdStr.rstrip(';')
+                scmd = []
+                for cmd in self.cmd:
+                    scmd.append(utils.GetCmdString(self.cmd))
+                return ';'.join(scmd)
             else:
-                return ' '.join(self.cmdlist)
+                return utils.GetCmdString(self.cmd)
         else:
-            return self.cmdlist
+            return self.cmd
 
     def GetType(self):
         """Get map layer type"""
@@ -256,11 +258,7 @@
     def SetName(self, name):
         """Set layer name"""
         self.name = name
-
-    def SetCmd(self, cmd):
-        """Set layer name"""
-        self.cmdlist = cmd
-
+        
     def SetActive(self, enable=True):
         """Active or deactive layer"""
         self.active = bool(enable)
@@ -280,7 +278,7 @@
         
     def SetCmd(self, cmd):
         """Set new command for layer"""
-        self.cmdlist = cmd
+        self.cmd = utils.CmdToTuple(cmd)
         Debug.msg(3, "Layer.SetCmd(): cmd='%s'" % self.GetCmd(string=True))
         
         # for re-rendering
@@ -591,32 +589,35 @@
             os.environ["GISRC"] = self.gisrc
 
         # do not update & shell style output
-        cmdList = ["g.region", "-u", "-g", "-p", "-c"]
+        cmd = {}
+        cmd['flags'] = 'ugpc'
 
         if default:
-            cmdList.append('-d')
+            cmd['flags'] += 'd'
             
         if n:
-            cmdList.append('n=%s' % n)
+            cmd['n'] = n
         if s:
-            cmdList.append('s=%s' % s)
+            cmd['s'] = s
         if e:
-            cmdList.append('e=%s' % e)
+            cmd['e'] = e
         if w:
-            cmdList.append('w=%s' % w)
+            cmd['w'] = w
 
         if rast:
             if zoom:
-                cmdList.append('zoom=%s' % ','.join(rast))
+                cmd['zoom'] = rast[0]
             else:
-                cmdList.append('rast=%s' % ','.join(rast))
+                cmd['rast'] = ','.join(rast)
 
         if vect:
-            cmdList.append('vect=%s' % ','.join(vect))
+            cmd['vect'] = ','.join(vect)
         
-        try:
-            cmdRegion = gcmd.Command(cmdList)
-        except gcmd.CmdError, e:
+        ret = gcmd.RunCommand('g.region',
+                              read = True,
+                              **cmd)
+        if not ret:
+            e  = gcmd.CmdError(cmd = 'g.region', message = '')
             if rast:
                 e.message = _("Unable to zoom to raster map <%s>.") % rast[0] + \
                 '%s%s' % (os.linesep, os.linesep) + e.message
@@ -627,7 +628,7 @@
             print >> sys.stderr, e
             return self.region
 
-        for reg in cmdRegion.ReadStdOutput():
+        for reg in ret.splitlines():
             key, val = reg.split("=", 1)
             try:
                 region[key] = float(val)

Modified: grass/trunk/gui/wxpython/gui_modules/toolbars.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/toolbars.py	2009-02-02 19:28:57 UTC (rev 35737)
+++ grass/trunk/gui/wxpython/gui_modules/toolbars.py	2009-02-02 21:12:54 UTC (rev 35738)
@@ -1034,8 +1034,10 @@
             else:
                 openVectorMap = None
             mapName = gdialogs.CreateNewVector(self.parent,
-                                               exceptMap=openVectorMap, log=self.log,
-                                               cmdDef=(['v.edit', 'tool=create'], "map"),
+                                               exceptMap = openVectorMap, log = self.log,
+                                               cmd = (('v.edit',
+                                                       { 'tool' : 'create' },
+                                                       'map')),
                                                disableAdd=True)[0]
             if mapName:
                 # add layer to map layer tree

Modified: grass/trunk/gui/wxpython/gui_modules/utils.py
===================================================================
--- grass/trunk/gui/wxpython/gui_modules/utils.py	2009-02-02 19:28:57 UTC (rev 35737)
+++ grass/trunk/gui/wxpython/gui_modules/utils.py	2009-02-02 21:12:54 UTC (rev 35738)
@@ -65,7 +65,7 @@
                         layerType=None):
     """Get map name from GRASS command
 
-    @param dcmd GRASS command (given as list)
+    @param dcmd GRASS command (given as tuple)
     @param fullyQualified change map name to be fully qualified
     @param force parameter otherwise 'input'/'map'
     @param update change map name in command
@@ -76,7 +76,7 @@
     """
     mapname = ''
 
-    if len(dcmd) < 1:
+    if not dcmd:
         return mapname
     
     if 'd.grid' == dcmd[0]:
@@ -201,38 +201,27 @@
     @return list of mapsets
     """
     mapsets = []
-
-    ### FIXME
-    # problem using Command here (see preferences.py)
-    # cmd = gcmd.Command(['g.mapsets', '-l'])
+    
     if all:
-        cmd = subprocess.Popen(['g.mapsets' + globalvar.EXT_BIN, '-l'],
-                               stdout=subprocess.PIPE)
+        ret = gcmd.RunCommand('g.mapsets',
+                              read = True,
+                              flags = 'l')
     
-        try:
-            # for mset in cmd.ReadStdOutput()[0].split(' '):
-            for line in cmd.stdout.readlines():
-                for mset in line.strip('%s' % os.linesep).split(' '):
-                    if len(mset) == 0:
-                        continue
-                    mapsets.append(mset)
-        except:
-            raise gcmd.CmdError(_('Unable to get list of available mapsets.'))
-    
+        if ret:
+            mapsets = ret.rstrip('\n').split(' ')
+        else:
+            raise gcmd.CmdError(cmd = 'g.mapsets',
+                                message = _('Unable to get list of available mapsets.'))
     else:
-        # cmd = gcmd.Command(['g.mapsets', '-p'])
-        cmd = subprocess.Popen(['g.mapsets' + globalvar.EXT_BIN, '-p'],
-                               stdout=subprocess.PIPE)
-        try:
-            # for mset in cmd.ReadStdOutput()[0].split(' '):
-            for line in cmd.stdout.readlines():
-                for mset in line.strip('%s' % os.linesep).split(' '):
-                    if len(mset) == 0:
-                        continue
-                    mapsets.append(mset)
-        except:
-            raise gcmd.CmdError(_('Unable to get list of accessible mapsets.'))
-
+        ret = gcmd.RunCommand('g.mapsets',
+                              read = True,
+                              flags = 'p')
+        if ret:
+            mapsets = ret.rstrip('\n').split(' ')
+        else:
+            raise gcmd.CmdError(cmd = 'g.mapsets',
+                                message = _('Unable to get list of accessible mapsets.'))
+        
         ListSortLower(mapsets)
     
     return mapsets
@@ -331,6 +320,40 @@
     
     return str(d) + ':' + m + ':' + s
 
+def GetCmdString(cmd):
+    """
+    Get GRASS command as string.
+    
+    @param cmd GRASS command given as tuple
+    
+    @return command string
+    """
+    scmd = ''
+    if not cmd:
+        return ''
+    scmd = cmd[0]
+    for k, v in cmd[1].iteritems():
+        scmd += ' %s=%s' % (k, v)
+    return scmd
+
+def CmdToTuple(self, cmd):
+    """Convert command list to tuple for gcmd.RunCommand()"""
+    if len(cmd) < 1:
+        return None
+        
+    dcmd = {}
+    for item in cmd[1:]:
+        if '=' in item:
+            key, value = item.split('=')
+            dcmd[str(key)] = str(value)
+        else: # -> flags
+            if not dmcd.has_key('flags'):
+                dcmd['flags'] = ''
+            dmcd['flags'] += item.replace('-', '')
+                
+    return (cmd[0],
+            dcmd)
+
 def reexec_with_pythonw():
     """Re-execute Python on Mac OS"""
     if sys.platform == 'darwin' and \

Modified: grass/trunk/gui/wxpython/wxgui.py
===================================================================
--- grass/trunk/gui/wxpython/wxgui.py	2009-02-02 19:28:57 UTC (rev 35737)
+++ grass/trunk/gui/wxpython/wxgui.py	2009-02-02 21:12:54 UTC (rev 35738)
@@ -514,9 +514,11 @@
 
     def OnNewVector(self, event):
         """Create new vector map layer"""
-        name, add = gdialogs.CreateNewVector(self, log=self.goutput,
-                                             cmdDef=(['v.edit', 'tool=create'], "map"))
-
+        name, add = gdialogs.CreateNewVector(self, log = self.goutput,
+                                             cmd = (('v.edit',
+                                                     { 'tool' : 'create' },
+                                                     'map')))
+        
         if name and add:
             # add layer to map layer tree
             self.curr_page.maptree.AddLayer(ltype='vector',



More information about the grass-commit mailing list