def _clean(self, llist): for layer in llist: if layer.maskfile: try_remove(layer.maskfile) if layer.mapfile: try_remove(layer.mapfile) llist.remove(layer)
def finish(): """Terminate the GRASS session and clean up GRASS commands can no longer be used after this function has been called Basic usage:: import grass.script as gs gs.setup.finish() The function is not completely symmetrical with :func:`init` because it only closes the mapset, but doesn't undo the runtime environment setup. """ clean_default_db() clean_temp() # TODO: unlock the mapset? # unset the GISRC and delete the file from grass.script import utils as gutils gutils.try_remove(os.environ["GISRC"]) os.environ.pop("GISRC") # remove gislock env var (not the gislock itself os.environ.pop("GIS_LOCK")
def OnExit(self): if __name__ == "__main__": # stop the timer # self.timer.Stop() # terminate thread for f in monFile.itervalues(): try_remove(f)
def Render(self, cmd, env): """If it is needed, download missing WMS data. .. todo:: lmgr deletes mapfile and maskfile when order of layers was changed (drag and drop) - if deleted, fetch data again """ if not haveGdal: return env = copy.copy(env) self.dstSize['cols'] = int(env["GRASS_WIDTH"]) self.dstSize['rows'] = int(env["GRASS_HEIGHT"]) region = self._getRegionDict(env) self._fitAspect(region, self.dstSize) self.updateMap = True fetchData = False zoomChanged = False if self.renderedRegion is None or \ cmd != self.fetched_data_cmd: fetchData = True else: for c in ['north', 'south', 'east', 'west']: if self.renderedRegion and \ region[c] != self.renderedRegion[c]: fetchData = True break for c in ['e-w resol', 'n-s resol']: if self.renderedRegion and \ region[c] != self.renderedRegion[c]: zoomChanged = True break if fetchData: self.fetched_data_cmd = None self.renderedRegion = region try_remove(self.mapfile) try_remove(self.tempMap) self.currentPid = self.thread.GetId() self.thread.abort() self.downloading = True self.fetching_cmd = cmd cmdList = utils.CmdTupleToList(cmd) if Debug.GetLevel() < 3: cmdList.append('--quiet') env["GRASS_PNGFILE"] = self.tempMap env["GRASS_REGION"] = self._createRegionStr(region) self.thread.RunCmd(cmdList, env=env, stderr=self.cmdStdErr)
def Render(self, cmd, env): """If it is needed, download missing WMS data. .. todo:: lmgr deletes mapfile and maskfile when order of layers was changed (drag and drop) - if deleted, fetch data again """ if not haveGdal: return env = copy.copy(env) self.dstSize['cols'] = int(env["GRASS_RENDER_WIDTH"]) self.dstSize['rows'] = int(env["GRASS_RENDER_HEIGHT"]) region = self._getRegionDict(env) self._fitAspect(region, self.dstSize) self.updateMap = True fetchData = False zoomChanged = False if self.renderedRegion is None or \ cmd != self.fetched_data_cmd: fetchData = True else: for c in ['north', 'south', 'east', 'west']: if self.renderedRegion and \ region[c] != self.renderedRegion[c]: fetchData = True break for c in ['e-w resol', 'n-s resol']: if self.renderedRegion and \ region[c] != self.renderedRegion[c]: zoomChanged = True break if fetchData: self.fetched_data_cmd = None self.renderedRegion = region try_remove(self.mapfile) try_remove(self.tempMap) self.currentPid = self.thread.GetId() self.thread.abort() self.downloading = True self.fetching_cmd = cmd cmdList = utils.CmdTupleToList(cmd) if Debug.GetLevel() < 3: cmdList.append('--quiet') env["GRASS_RENDER_FILE"] = self.tempMap env["GRASS_REGION"] = self._createRegionStr(region) self.thread.RunCmd(cmdList, env=env, stderr=self.cmdStdErr)
def main(): input = options['input'] layer = options['layer'] format = options['format'] dsn = options['dsn'] table = options['table'] if format.lower() == 'dbf': format = "ESRI_Shapefile" if format.lower() == 'csv': olayer = basename(dsn, 'csv') else: olayer = None #is there a simpler way of testing for --overwrite? dbffile = input + '.dbf' if os.path.exists(dbffile) and not grass.overwrite(): grass.fatal(_("File <%s> already exists") % dbffile) if olayer: if grass.run_command('v.out.ogr', quiet=True, input=input, layer=layer, dsn=dsn, format=format, type='point,line,area', olayer=olayer) != 0: sys.exit(1) else: if grass.run_command('v.out.ogr', quiet=True, input=input, layer=layer, dsn=dsn, format=format, type='point,line,area') != 0: sys.exit(1) if format == "ESRI_Shapefile": exts = ['shp', 'shx', 'prj'] if dsn.endswith('.dbf'): outname = basename(dsn, 'dbf') for ext in exts: try_remove("%s.%s" % (outname, ext)) outname += '.dbf' else: for ext in exts: try_remove(os.path.join(dsn, "%s.%s" % (input, ext))) outname = os.path.join(dsn, input + ".dbf") elif format.lower() == 'csv': outname = dsn + '.csv' else: outname = input grass.message(_("Exported table <%s>") % outname)
def Render(self): """Render layer to image :return: rendered image filename :return: None on error or if cmdfile is defined """ if not self.cmd: return None # ignore in 2D if self.type == '3d-raster': return None Debug.msg (3, "Layer.Render(): type=%s, name=%s" % \ (self.type, self.name)) # prepare command for each layer layertypes = utils.command2ltype.values() + ['overlay', 'command'] if self.type not in layertypes: raise GException(_("<%(name)s>: layer type <%(type)s> is not supported") % \ {'type' : self.type, 'name' : self.name}) if self.mapfile: self.environ["GRASS_RENDER_FILE"] = self.mapfile # execute command try: if self.type == 'command': read = False for c in self.cmd: ret, msg = self._runCommand(c) if ret != 0: break if not read: self.environ["GRASS_RENDER_FILE_READ"] = "TRUE" self.environ["GRASS_RENDER_FILE_READ"] = "FALSE" else: ret, msg = self._runCommand(self.cmd) if ret != 0: sys.stderr.write(_("Command '%s' failed\n") % self.GetCmd(string = True)) if msg: sys.stderr.write(_("Details: %s\n") % msg) raise GException() except GException: # clean up after problems for f in [self.mapfile, self.maskfile]: if not f: continue try_remove(f) f = None self.forceRender = False return self.mapfile
def OnExit(self): if __name__ == "__main__": # stop the timer if self.timer.IsRunning: self.timer.Stop() # terminate thread for f in six.itervalues(monFile): try_remove(f) return True
def Render(self): """Render layer to image :return: rendered image filename :return: None on error or if cmdfile is defined """ if not self.cmd: return None # ignore in 2D if self.type == '3d-raster': return None Debug.msg (3, "Layer.Render(): type=%s, name=%s" % \ (self.type, self.name)) # prepare command for each layer layertypes = utils.command2ltype.values() + ['overlay', 'command'] if self.type not in layertypes: raise GException(_("<%(name)s>: layer type <%(type)s> is not supported") % \ {'type' : self.type, 'name' : self.name}) if self.mapfile: self.environ["GRASS_PNGFILE"] = self.mapfile # execute command try: if self.type == 'command': read = False for c in self.cmd: ret, msg = self._runCommand(c) if ret != 0: break if not read: self.environ["GRASS_PNG_READ"] = "TRUE" self.environ["GRASS_PNG_READ"] = "FALSE" else: ret, msg = self._runCommand(self.cmd) if ret != 0: sys.stderr.write(_("Command '%s' failed\n") % self.GetCmd(string = True)) if msg: sys.stderr.write(_("Details: %s\n") % msg) raise GException() except GException: # clean up after problems for f in [self.mapfile, self.maskfile]: if not f: continue try_remove(f) f = None self.forceRender = False return self.mapfile
def _runAnDone(self, cmd, returncode): """Called when analysis is done""" self.tmp_maps.DeleteTmpMap(self.tmpInPts) #TODO remove earlier (OnDone lambda?) self.tmp_maps.DeleteTmpMap(self.tmpInPtsConnected) try_remove(self.tmpPtsAsciiFile) if cmd[0] == "v.net.flow": self.tmp_maps.DeleteTmpMap(self.vnetFlowTmpCut) self._onDone(cmd, returncode)
def create_location_interactively(guiparent, grassdb): """ Create new location using Location Wizard. Returns tuple (database, location, mapset) where mapset is "PERMANENT" by default or another mapset a user created and may want to switch to. """ from location_wizard.wizard import LocationWizard gWizard = LocationWizard(parent=guiparent, grassdatabase=grassdb) if gWizard.location is None: gWizard_output = (None, None, None) # Returns Nones after Cancel return gWizard_output if gWizard.georeffile: message = _( "Do you want to import {} " "to the newly created location?" ).format(gWizard.georeffile) dlg = wx.MessageDialog(parent=guiparent, message=message, caption=_("Import data?"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION) dlg.CenterOnParent() if dlg.ShowModal() == wx.ID_YES: gisrc_file, env = create_environment(gWizard.grassdatabase, gWizard.location, 'PERMANENT') import_file(guiparent, gWizard.georeffile, env) try_remove(gisrc_file) dlg.Destroy() if gWizard.default_region: defineRegion = RegionDef(guiparent, location=gWizard.location) defineRegion.CenterOnParent() defineRegion.ShowModal() defineRegion.Destroy() if gWizard.user_mapset: mapset = create_mapset_interactively(guiparent, gWizard.grassdatabase, gWizard.location) # Returns database and location created by user # and a mapset user may want to switch to gWizard_output = (gWizard.grassdatabase, gWizard.location, mapset) else: # Returns PERMANENT mapset when user mapset not defined gWizard_output = (gWizard.grassdatabase, gWizard.location, "PERMANENT") return gWizard_output
def main(): input = options['input'] layer = options['layer'] format = options['format'] output = options['output'] table = options['table'] if format.lower() == 'dbf': format = "ESRI_Shapefile" if format.lower() == 'csv': olayer = basename(output, 'csv') else: olayer = None #is there a simpler way of testing for --overwrite? dbffile = input + '.dbf' if os.path.exists(dbffile) and not grass.overwrite(): grass.fatal(_("File <%s> already exists") % dbffile) if olayer: try: grass.run_command('v.out.ogr', quiet=True, input=input, layer=layer, output=output, format=format, type='point,line,area', olayer=olayer) except CalledModuleError: grass.fatal(_("Module <%s> failed") % 'v.out.ogr') else: try: grass.run_command('v.out.ogr', quiet=True, input=input, layer=layer, output=output, format=format, type='point,line,area') except CalledModuleError: grass.fatal(_("Module <%s> failed") % 'v.out.ogr') if format == "ESRI_Shapefile": exts = ['shp', 'shx', 'prj'] if output.endswith('.dbf'): outname = basename(output, 'dbf') for ext in exts: try_remove("%s.%s" % (outname, ext)) outname += '.dbf' else: for ext in exts: try_remove(os.path.join(output, "%s.%s" % (input, ext))) outname = os.path.join(output, input + ".dbf") elif format.lower() == 'csv': outname = output + '.csv' else: outname = input grass.message(_("Exported table <%s>") % outname)
def _runAnDone(self, event): """Called when analysis is done""" self.tmp_maps.DeleteTmpMap( self.tmpInPts) # TODO remove earlier (OnDone lambda?) self.tmp_maps.DeleteTmpMap(self.tmpInPtsConnected) try_remove(self.tmpPtsAsciiFile) if event.cmd[0] == "v.net.flow": self.tmp_maps.DeleteTmpMap(self.vnetFlowTmpCut) self._onDone(event)
def main(): input = options['input'] layer = options['layer'] format = options['format'] output = options['output'] table = options['table'] if format.lower() == 'dbf': format = "ESRI_Shapefile" if format.lower() == 'csv': olayer = basename(output, 'csv') else: olayer = None # is there a simpler way of testing for --overwrite? dbffile = input + '.dbf' if os.path.exists(dbffile) and not gcore.overwrite(): gcore.fatal(_("File <%s> already exists") % dbffile) if olayer: try: gcore.run_command('v.out.ogr', quiet=True, input=input, layer=layer, output=output, format=format, type='point,line,area', olayer=olayer) except CalledModuleError: gcore.fatal(_("Module <%s> failed") % 'v.out.ogr') else: try: gcore.run_command('v.out.ogr', quiet=True, input=input, layer=layer, output=output, format=format, type='point,line,area') except CalledModuleError: gcore.fatal(_("Module <%s> failed") % 'v.out.ogr') if format == "ESRI_Shapefile": exts = ['shp', 'shx', 'prj'] if output.endswith('.dbf'): outname = basename(output, 'dbf') for ext in exts: try_remove("%s.%s" % (outname, ext)) outname += '.dbf' else: for ext in exts: try_remove(os.path.join(output, "%s.%s" % (input, ext))) outname = os.path.join(output, input + ".dbf") elif format.lower() == 'csv': outname = output + '.csv' else: outname = input gcore.message(_("Exported table <%s>") % outname)
def Render(self, env=None): """Render layer to image :return: rendered image filename :return: None on error or if cmdfile is defined """ if not self.cmd: return None # ignore in 2D if self.type == 'raster_3d': return None Debug.msg(3, "Layer.Render(): type=%s, name=%s, file=%s" % (self.type, self.name, self.mapfile)) # prepare command for each layer layertypes = utils.command2ltype.values() + ['overlay', 'command'] if self.type not in layertypes: raise GException( _("<%(name)s>: layer type <%(type)s> is not supported") % {'type': self.type, 'name': self.name}) if not env: env = os.environ.copy() # render layers try: if self.type == 'command': first = True for c in self.cmd: self.renderMgr.Render(c, env) if first: env["GRASS_RENDER_FILE_READ"] = "TRUE" first = False else: self.renderMgr.Render(self.cmd, env) except GException: sys.stderr.write( _("Command '%s' failed\n") % self.GetCmd( string=True)) sys.stderr.write(_("Details: %s\n") % e) # clean up after problems for f in [self.mapfile, self.maskfile]: if not f: continue try_remove(f) f = None return self.mapfile
def Render(self, env=None): """Render layer to image :return: rendered image filename :return: None on error or if cmdfile is defined """ if not self.cmd: return None # ignore in 2D if self.type == 'raster_3d': return None Debug.msg (3, "Layer.Render(): type=%s, name=%s, file=%s" % \ (self.type, self.name, self.mapfile)) # prepare command for each layer layertypes = utils.command2ltype.values() + ['overlay', 'command'] if self.type not in layertypes: raise GException(_("<%(name)s>: layer type <%(type)s> is not supported") % \ {'type' : self.type, 'name' : self.name}) if not env: env = os.environ.copy() # render layers try: if self.type == 'command': first = True for c in self.cmd: self.renderMgr.Render(c, env) if first: env["GRASS_RENDER_FILE_READ"] = "TRUE" first = False else: self.renderMgr.Render(self.cmd, env) except GException: sys.stderr.write( _("Command '%s' failed\n") % self.GetCmd(string=True)) sys.stderr.write(_("Details: %s\n") % e) # clean up after problems for f in [self.mapfile, self.maskfile]: if not f: continue try_remove(f) f = None return self.mapfile
def main(): # check if input file exists infile = options['input'] gfile = grass.find_file(infile, element='vector') if not gfile['name']: grass.fatal(_("Vector map <%s> not found") % infile) # create tempfile and write ascii file of input temp_in = grass.tempfile() try: grass.run_command('v.out.ascii', overwrite=True, input=gfile['name'], output=temp_in) except CalledModuleError: grass.fatal(_("Failed to export vector in a temporary file")) # x and y of median point medx, medy = point_med(temp_in) try_remove(temp_in) # prepare the output output = "%f|%f" % (medx, medy) map_name = options['output'] overwrite = os.getenv('GRASS_OVERWRITE') # if output is not set return to stdout if map_name == '-': grass.message(output) # else else: # output file goutfile = grass.find_file(name=map_name, element='vector', mapset='.') # output tempfile temp_out = grass.tempfile() file_out = open(temp_out, 'w') file_out.write(output) file_out.close() # output file exists and not overwrite if goutfile['file'] and overwrite != '1': grass.fatal(_("Vector map <%s> already exists") % map_name) # output file exists and overwrite elif goutfile['file'] and overwrite == '1': grass.warning( _("Vector map <%s> already exists and will be overwritten") % map_name) grass.run_command('v.in.ascii', overwrite=True, input=temp_out, output=map_name) # output file not exists else: grass.run_command('v.in.ascii', input=temp_out, output=map_name) try_remove(temp_out)
def _updateTtbByGlobalCosts(self, vectMapName, tlayer): # TODO get layer number do not use it directly intervals = self.turnsData["global"].GetData() cmdUpdGlob = [ "v.db.update", "map=", self.inputData["input"].GetValue(), "layer=%d" % tlayer, "column=cost", ] dbInfo = VectorDBInfo(vectMapName) table = dbInfo.GetTable(tlayer) driver, database = dbInfo.GetDbSettings(tlayer) sqlFile = grass.tempfile() sqlFile_f = open(sqlFile, "w") for ival in intervals: from_angle = ival[0] to_angle = ival[1] cost = ival[2] if to_angle < from_angle: to_angle = math.pi * 2 + to_angle # if angle < from_angle: # angle = math.pi * 2 + angle where = " WHERE (((angle < {0}) AND ({2} + angle >= {0} AND {2} + angle < {1})) OR \ ((angle >= {0}) AND (angle >= {0} AND angle < {1}))) AND cost==0.0 ".format( str(from_angle), str(to_angle), str(math.pi * 2)) stm = ("UPDATE %s SET cost=%f " % (table, cost)) + where + ";\n" sqlFile_f.write(stm) sqlFile_f.close() # TODO improve parser and run in thread ret, msg, err = RunCommand( "db.execute", getErrorMsg=True, input=sqlFile, read=True, driver=driver, database=database, ) try_remove(sqlFile)
def OnRemove(self, event): """Remove configuration file from path and update the list""" confile = self.listfiles[self.listfileBox.GetSelections()[0]] dlg = wx.MessageDialog(parent=self.parent, message=_("Do you want remove r.li " \ "configuration file <%s>?") % confile, caption=_("Remove new r.li configuration file?"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION) if dlg.ShowModal() == wx.ID_YES: self.listfileBox.Delete(self.listfileBox.GetSelections()[0]) try_remove(os.path.join(self.rlipath, confile)) self.listfiles = self.ListFiles() dlg.Destroy() return
def _updateTtbByGlobalCosts(self, vectMapName, tlayer): #TODO get layer number do not use it directly intervals = self.turnsData["global"].GetData() cmdUpdGlob = [ "v.db.update", "map=", self.inputData["input"].GetValue(), "layer=%d" % tlayer, "column=cost", ] dbInfo = VectorDBInfo(vectMapName) table = dbInfo.GetTable(tlayer) driver, database = dbInfo.GetDbSettings(tlayer) sqlFile = grass.tempfile() sqlFile_f = open(sqlFile, 'w') for ival in intervals: from_angle = ival[0] to_angle = ival[1] cost = ival[2] if to_angle < from_angle: to_angle = math.pi * 2 + to_angle #if angle < from_angle: # angle = math.pi * 2 + angle where = " WHERE (((angle < {0}) AND ({2} + angle >= {0} AND {2} + angle < {1})) OR \ ((angle >= {0}) AND (angle >= {0} AND angle < {1}))) AND cost==0.0 ".format(str(from_angle), str(to_angle), str(math.pi * 2)) stm = ("UPDATE %s SET cost=%f " % (table, cost)) + where + ";\n"; sqlFile_f.write(stm) sqlFile_f.close() #TODO imporve parser and run in thread ret, msg, err = RunCommand('db.execute', getErrorMsg = True, input = sqlFile, read = True, driver = driver, database = database) try_remove(sqlFile)
def SaveAs(self): """Save python script to file""" if self.tempfile: try_remove(self.filename) self.tempfile = False filename = None dlg = wx.FileDialog( parent=self.guiparent, message=_("Choose file to save"), defaultDir=os.getcwd(), wildcard=_("Python script (*.py)|*.py"), style=wx.FD_SAVE, ) if dlg.ShowModal() == wx.ID_OK: filename = dlg.GetPath() if not filename: return # check for extension if filename[-3:] != ".py": filename += ".py" if os.path.exists(filename): dlg = wx.MessageDialog( parent=self.guiparent, message=_("File <%s> already exists. " "Do you want to overwrite this file?") % filename, caption=_("Save file"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION, ) if dlg.ShowModal() == wx.ID_NO: dlg.Destroy() return dlg.Destroy() self.filename = filename self.tempfile = False self.Save()
def finish(): """Terminate the GRASS session and clean up GRASS commands can no longer be used after this function has been called Basic usage:: import grass.script as gs gs.setup.cleanup() """ clean_default_db() clean_temp() # TODO: unlock the mapset? # unset the GISRC and delete the file from grass.script import utils as gutils gutils.try_remove(os.environ['GISRC']) os.environ.pop('GISRC') # remove gislock env var (not the gislock itself os.environ.pop('GIS_LOCK')
def SaveAs(self): """Save python script to file""" if self.tempfile: try_remove(self.filename) self.tempfile = False filename = None dlg = wx.FileDialog(parent=self.guiparent, message=_("Choose file to save"), defaultDir=os.getcwd(), wildcard=_("Python script (*.py)|*.py"), style=wx.FD_SAVE) if dlg.ShowModal() == wx.ID_OK: filename = dlg.GetPath() if not filename: return # check for extension if filename[-3:] != ".py": filename += ".py" if os.path.exists(filename): dlg = wx.MessageDialog( parent=self.guiparent, message=_("File <%s> already exists. " "Do you want to overwrite this file?") % filename, caption=_("Save file"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION) if dlg.ShowModal() == wx.ID_NO: dlg.Destroy() return dlg.Destroy() self.filename = filename self.tempfile = False self.Save()
def SaveHistStep(self): """Create new history step with data in buffer""" self.maxHistSteps = UserSettings.Get(group='vnet', key='other', subkey='max_hist_steps') self.currHistStep = 0 newHistFile = grass.tempfile() newHist = open(newHistFile, "w") self._saveNewHistStep(newHist) oldHist = open(self.histFile) removedHistData = self._savePreviousHist(newHist, oldHist) oldHist.close() newHist.close() try_remove(self.histFile) self.histFile = newHistFile self.newHistStepData.clear() return removedHistData
def SaveHistStep(self): """Create new history step with data in buffer""" self.maxHistSteps = UserSettings.Get( group="vnet", key="other", subkey="max_hist_steps" ) self.currHistStep = 0 newHistFile = grass.tempfile() newHist = open(newHistFile, "w") self._saveNewHistStep(newHist) oldHist = open(self.histFile) removedHistData = self._savePreviousHist(newHist, oldHist) oldHist.close() newHist.close() try_remove(self.histFile) self.histFile = newHistFile self.newHistStepData.clear() return removedHistData
def main(): layers = options['map'].split(',') if len(layers) < 2: grass.error(_("At least 2 maps are required")) tmpfile = grass.tempfile() for map in layers: if not grass.find_file(map, element='cell')['file']: grass.fatal(_("Raster map <%s> not found") % map) grass.write_command('d.text', color='black', size=4, line=1, stdin="CORRELATION") os.environ['GRASS_PNG_READ'] = 'TRUE' colors = "red black blue green gray violet".split() line = 2 iloop = 0 jloop = 0 for iloop, i in enumerate(layers): for jloop, j in enumerate(layers): if i != j and iloop <= jloop: color = colors[0] colors = colors[1:] colors.append(color) grass.write_command('d.text', color=color, size=4, line=line, stdin="%s %s" % (i, j)) line += 1 ofile = file(tmpfile, 'w') grass.run_command('r.stats', flags='cnA', input=(i, j), stdout=ofile) ofile.close() ifile = file(tmpfile, 'r') first = True for l in ifile: f = l.rstrip('\r\n').split(' ') x = float(f[0]) y = float(f[1]) if first: minx = maxx = x miny = maxy = y first = False if minx > x: minx = x if maxx < x: maxx = x if miny > y: miny = y if maxy < y: maxy = y ifile.close() kx = 100.0 / (maxx - minx + 1) ky = 100.0 / (maxy - miny + 1) p = grass.feed_command('d.graph', color=color) ofile = p.stdin ifile = file(tmpfile, 'r') for l in ifile: f = l.rstrip('\r\n').split(' ') x = float(f[0]) y = float(f[1]) ofile.write("icon + 0.1 %f %f\n" % ((x - minx + 1) * kx, (y - miny + 1) * ky)) ifile.close() ofile.close() p.wait() try_remove(tmpfile)
def cleanup(): try_remove(tmp) try_remove(tmp + '.dig')
def main(): layers = options["map"].split(",") if len(layers) < 2: gcore.error(_("At least 2 maps are required")) tmpfile = gcore.tempfile() for map in layers: if not gcore.find_file(map, element="cell")["file"]: gcore.fatal(_("Raster map <%s> not found") % map) try: gcore.write_command( "d.text", color="black", size=4, line=1, stdin="CORRELATION" ) except CalledModuleError: return 1 os.environ["GRASS_RENDER_FILE_READ"] = "TRUE" colors = "red black blue green gray violet".split() line = 2 iloop = 0 jloop = 0 for iloop, i in enumerate(layers): for jloop, j in enumerate(layers): if i != j and iloop <= jloop: color = colors[0] colors = colors[1:] colors.append(color) gcore.write_command( "d.text", color=color, size=4, line=line, stdin="%s %s" % (i, j) ) line += 1 ofile = open(tmpfile, "w") gcore.run_command("r.stats", flags="cnA", input=(i, j), stdout=ofile) ofile.close() ifile = open(tmpfile, "r") first = True for line in ifile: f = line.rstrip("\r\n").split(" ") x = float(f[0]) y = float(f[1]) if first: minx = maxx = x miny = maxy = y first = False if minx > x: minx = x if maxx < x: maxx = x if miny > y: miny = y if maxy < y: maxy = y ifile.close() kx = 100.0 / (maxx - minx + 1) ky = 100.0 / (maxy - miny + 1) p = gcore.feed_command("d.graph", color=color) ofile = p.stdin ifile = open(tmpfile, "r") for line in ifile: f = line.rstrip("\r\n").split(" ") x = float(f[0]) y = float(f[1]) ofile.write( b"icon + 0.1 %f %f\n" % ((x - minx + 1) * kx, (y - miny + 1) * ky) ) ifile.close() ofile.close() p.wait() try_remove(tmpfile) return 0
def main(): infile = options['input'] compression_off = flags['c'] mapset = None if '@' in infile: infile, mapset = infile.split('@') if options['output']: outfile_path, outfile_base = os.path.split(os.path.abspath(options['output'])) else: outfile_path, outfile_base = os.path.split(os.path.abspath(infile + ".pack")) outfile = os.path.join(outfile_path, outfile_base) global tmp tmp = grass.tempdir() tmp_dir = os.path.join(tmp, infile) os.mkdir(tmp_dir) grass.debug('tmp_dir = %s' % tmp_dir) gfile = grass.find_file(name = infile, element = 'cell', mapset = mapset) if not gfile['name']: grass.fatal(_("Raster map <%s> not found") % infile) if os.path.exists(outfile): if os.getenv('GRASS_OVERWRITE'): grass.warning(_("Pack file <%s> already exists and will be overwritten") % outfile) try_remove(outfile) else: grass.fatal(_("option <output>: <%s> exists.") % outfile) grass.message(_("Packing <%s> to <%s>...") % (gfile['fullname'], outfile)) basedir = os.path.sep.join(os.path.normpath(gfile['file']).split(os.path.sep)[:-2]) olddir = os.getcwd() # copy elements for element in ['cats', 'cell', 'cellhd', 'colr', 'fcell', 'hist']: path = os.path.join(basedir, element, infile) if os.path.exists(path): grass.debug('copying %s' % path) shutil.copyfile(path, os.path.join(tmp_dir, element)) if os.path.exists(os.path.join(basedir, 'cell_misc', infile)): shutil.copytree(os.path.join(basedir, 'cell_misc', infile), os.path.join(tmp_dir, 'cell_misc')) if not os.listdir(tmp_dir): grass.fatal(_("No raster map components found")) # copy projection info # (would prefer to use g.proj*, but this way is 5.3 and 5.7 compat) gisenv = grass.gisenv() for support in ['INFO', 'UNITS', 'EPSG']: path = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'], 'PERMANENT', 'PROJ_' + support) if os.path.exists(path): shutil.copyfile(path, os.path.join(tmp_dir, 'PROJ_' + support)) # pack it all up os.chdir(tmp) if compression_off: tar = tarfile.TarFile.open(name = outfile_base, mode = 'w:') else: tar = tarfile.TarFile.open(name = outfile_base, mode = 'w:gz') tar.add(infile, recursive = True) tar.close() try: shutil.move(outfile_base, outfile) except shutil.Error as e: grass.fatal(e) os.chdir(olddir) grass.verbose(_("Raster map saved to '%s'" % outfile))
def toolboxesOutdated(): """Removes auto-generated menudata.xml to let gui regenerate it next time it starts.""" path = os.path.join(GetSettingsPath(), 'toolboxes', 'menudata.xml') if os.path.exists(path): try_remove(path)
def main(): infile = options['input'] compression_off = flags['c'] global basedir basedir = grass.tempdir() # check if vector map exists gfile = grass.find_file(infile, element='vector') if not gfile['name']: grass.fatal(_("Vector map <%s> not found") % infile) # check if input vector map is in the native format if vector.vector_info(gfile['fullname'])['format'] != 'native': grass.fatal( _("Unable to pack vector map <%s>. Only native format supported.") % gfile['fullname']) # split the name if there is the mapset name if infile.find('@'): infile = infile.split('@')[0] # output name if options['output']: outfile = options['output'] else: outfile = infile + '.pack' # check if exists the output file if os.path.exists(outfile): if os.getenv('GRASS_OVERWRITE'): grass.warning( _("Pack file <%s> already exists and will be overwritten") % outfile) try_remove(outfile) else: grass.fatal(_("option <%s>: <%s> exists.") % ("output", outfile)) # prepare for packing grass.verbose(_("Packing <%s>...") % (gfile['fullname'])) # write tar file, optional compression if compression_off: tar = tarfile.open(name=outfile, mode='w:') else: tar = tarfile.open(name=outfile, mode='w:gz') tar.add(gfile['file'], infile) # check if exist a db connection for the vector db_vect = vector.vector_db(gfile['fullname']) if not db_vect: grass.verbose( _('There is not database connected with vector map <%s>') % gfile['fullname']) else: # for each layer connection save a table in sqlite database sqlitedb = os.path.join(basedir, 'db.sqlite') for i, dbconn in db_vect.items(): grass.run_command('db.copy', from_driver=dbconn['driver'], from_database=dbconn['database'], from_table=dbconn['table'], to_driver='sqlite', to_database=sqlitedb, to_table=dbconn['table']) tar.add(sqlitedb, 'db.sqlite') # add to the tar file the PROJ files to check when unpack file gisenv = grass.gisenv() for support in ['INFO', 'UNITS', 'EPSG']: path = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'], 'PERMANENT', 'PROJ_' + support) if os.path.exists(path): tar.add(path, 'PROJ_' + support) tar.close() grass.message( _("Pack file <%s> created") % os.path.join(os.getcwd(), outfile))
def _vnetPathRunAnDone(self, event): """Called when v.net.path analysis is done""" try_remove(self.coordsTmpFile) self._onDone(event)
def main(): out = options['output'] wfs_url = options['url'] request_base = 'REQUEST=GetFeature&SERVICE=WFS&VERSION=1.0.0' wfs_url += request_base if options['name']: wfs_url += '&TYPENAME=' + options['name'] if options['srs']: wfs_url += '&SRS=' + options['srs'] if options['maximum_features']: wfs_url += '&MAXFEATURES=' + options['maximum_features'] if int(options['maximum_features']) < 1: grass.fatal('Invalid maximum number of features') if options['start_index']: wfs_url += '&STARTINDEX=' + options['start_index'] if int(options['start_index']) < 1: grass.fatal('Features begin with index "1"') if flags['r']: bbox = grass.read_command("g.region", flags='w').split('=')[1] wfs_url += '&BBOX=' + bbox if flags['l']: wfs_url = options[ 'url'] + 'REQUEST=GetCapabilities&SERVICE=WFS&VERSION=1.0.0' tmp = grass.tempfile() tmpxml = tmp + '.xml' grass.debug(wfs_url) grass.message(_("Retrieving data...")) inf = urllib.urlopen(wfs_url) outf = file(tmpxml, 'wb') while True: s = inf.read() if not s: break outf.write(s) inf.close() outf.close() if flags['l']: import shutil if os.path.exists('wms_capabilities.xml'): grass.fatal( 'A file called "wms_capabilities.xml" already exists here') # os.move() might fail if the temp file is on another volume, so we copy instead shutil.copy(tmpxml, 'wms_capabilities.xml') try_remove(tmpxml) sys.exit(0) grass.message(_("Importing data...")) ret = grass.run_command('v.in.ogr', flags='o', dsn=tmpxml, out=out) try_remove(tmpxml) if ret == 0: grass.message(_("Vector points map <%s> imported from WFS.") % out) else: grass.message(_("WFS import failed"))
def main(): infile = options['input'] compression_off = flags['c'] global basedir basedir = grass.tempdir() # check if vector map exists gfile = grass.find_file(infile, element = 'vector') if not gfile['name']: grass.fatal(_("Vector map <%s> not found") % infile) # check if input vector map is in the native format if vector.vector_info(gfile['fullname'])['format'] != 'native': grass.fatal(_("Unable to pack vector map <%s>. Only native format supported.") % \ gfile['fullname']) # split the name if there is the mapset name if infile.find('@'): infile = infile.split('@')[0] # output name if options['output']: outfile = options['output'] else: outfile = infile + '.pack' # check if exists the output file if os.path.exists(outfile): if os.getenv('GRASS_OVERWRITE'): grass.warning(_("Pack file <%s> already exists and will be overwritten") % outfile) try_remove(outfile) else: grass.fatal(_("option <%s>: <%s> exists.") % ("output", outfile)) # prepare for packing grass.verbose(_("Packing <%s>...") % (gfile['fullname'])) # write tar file, optional compression if compression_off: tar = tarfile.open(name = outfile, mode = 'w:') else: tar = tarfile.open(name = outfile, mode = 'w:gz') tar.add(gfile['file'], infile) # check if exist a db connection for the vector db_vect = vector.vector_db(gfile['fullname']) if not db_vect: grass.verbose(_('There is not database connected with vector map <%s>') % gfile['fullname']) else: # for each layer connection save a table in sqlite database sqlitedb = os.path.join(basedir, 'db.sqlite') for i, dbconn in db_vect.iteritems(): grass.run_command('db.copy', from_driver = dbconn['driver'], from_database = dbconn['database'], from_table = dbconn['table'], to_driver = 'sqlite', to_database = sqlitedb, to_table = dbconn['table']) tar.add(sqlitedb, 'db.sqlite') # add to the tar file the PROJ files to check when unpack file gisenv = grass.gisenv() for support in ['INFO', 'UNITS']: path = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'], 'PERMANENT', 'PROJ_' + support) if os.path.exists(path): tar.add(path, 'PROJ_' + support) tar.close() grass.message(_("Pack file <%s> created") % os.path.join(os.getcwd(), outfile))
def OnDone(self, event): """Python script finished""" if self.tempfile: try_remove(self.filename) self.filename = None self.running = False
def main(): layers = options['map'].split(',') if len(layers) < 2: grass.error(_("At least 2 maps are required")) tmpfile = grass.tempfile() for map in layers: if not grass.find_file(map, element = 'cell')['file']: grass.fatal(_("Raster map <%s> not found") % map) grass.write_command('d.text', color = 'black', size = 4, line = 1, stdin = "CORRELATION") os.environ['GRASS_PNG_READ'] = 'TRUE' colors = "red black blue green gray violet".split() line = 2 iloop = 0 jloop = 0 for iloop, i in enumerate(layers): for jloop, j in enumerate(layers): if i != j and iloop <= jloop: color = colors[0] colors = colors[1:] colors.append(color) grass.write_command('d.text', color = color, size = 4, line = line, stdin = "%s %s" % (i, j)) line += 1 ofile = file(tmpfile, 'w') grass.run_command('r.stats', flags = 'cnA', input = (i, j), stdout = ofile) ofile.close() ifile = file(tmpfile, 'r') first = True for l in ifile: f = l.rstrip('\r\n').split(' ') x = float(f[0]) y = float(f[1]) if first: minx = maxx = x miny = maxy = y first = False if minx > x: minx = x if maxx < x: maxx = x if miny > y: miny = y if maxy < y: maxy = y ifile.close() kx = 100.0/(maxx-minx+1) ky = 100.0/(maxy-miny+1) p = grass.feed_command('d.graph', color = color) ofile = p.stdin ifile = file(tmpfile, 'r') for l in ifile: f = l.rstrip('\r\n').split(' ') x = float(f[0]) y = float(f[1]) ofile.write("icon + 0.1 %f %f\n" % ((x-minx+1) * kx, (y-miny+1) * ky)) ifile.close() ofile.close() p.wait() try_remove(tmpfile)
def main(): infile = options['input'] compression_off = flags['c'] mapset = None if '@' in infile: infile, mapset = infile.split('@') if options['output']: outfile_path, outfile_base = os.path.split( os.path.abspath(options['output'])) else: outfile_path, outfile_base = os.path.split( os.path.abspath(infile + ".pack")) outfile = os.path.join(outfile_path, outfile_base) global tmp tmp = grass.tempdir() tmp_dir = os.path.join(tmp, infile) os.mkdir(tmp_dir) grass.debug('tmp_dir = %s' % tmp_dir) gfile = grass.find_file(name=infile, element='cell', mapset=mapset) if not gfile['name']: grass.fatal(_("Raster map <%s> not found") % infile) if os.path.exists(outfile): if os.getenv('GRASS_OVERWRITE'): grass.warning( _("Pack file <%s> already exists and will be overwritten") % outfile) try_remove(outfile) else: grass.fatal(_("option <output>: <%s> exists.") % outfile) grass.message(_("Packing <%s> to <%s>...") % (gfile['fullname'], outfile)) basedir = os.path.sep.join( os.path.normpath(gfile['file']).split(os.path.sep)[:-2]) olddir = os.getcwd() # copy elements info = grass.parse_command('r.info', flags='e', map=infile) vrt_files = {} if info['maptype'] == 'virtual': map_file = grass.find_file( name=infile, element='cell_misc', ) if map_file['file']: vrt = os.path.join(map_file['file'], 'vrt') if os.path.exists(vrt): with open(vrt, 'r') as f: for r in f.readlines(): map, mapset = r.split('@') map_basedir = os.path.sep.join( os.path.normpath(map_file['file'], ).split( os.path.sep)[:-2], ) vrt_files[map] = map_basedir for element in [ 'cats', 'cell', 'cellhd', 'cell_misc', 'colr', 'fcell', 'hist', ]: path = os.path.join(basedir, element, infile) if os.path.exists(path): grass.debug('copying %s' % path) if os.path.isfile(path): shutil.copyfile( path, os.path.join(tmp_dir, element), ) else: shutil.copytree( path, os.path.join(tmp_dir, element), ) # Copy vrt files if vrt_files: for f in vrt_files.keys(): f_tmp_dir = os.path.join(tmp, f) if not os.path.exists(f_tmp_dir): os.mkdir(f_tmp_dir) path = os.path.join(vrt_files[f], element, f) if os.path.exists(path): grass.debug("copying vrt file {}".format(path)) if os.path.isfile(path): shutil.copyfile( path, os.path.join(f_tmp_dir, element), ) else: shutil.copytree( path, os.path.join(f_tmp_dir, element), ) if not os.listdir(tmp_dir): grass.fatal(_("No raster map components found")) # copy projection info # (would prefer to use g.proj*, but this way is 5.3 and 5.7 compat) gisenv = grass.gisenv() for support in ['INFO', 'UNITS', 'EPSG']: path = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'], 'PERMANENT', 'PROJ_' + support) if os.path.exists(path): shutil.copyfile(path, os.path.join(tmp_dir, 'PROJ_' + support)) # pack it all up os.chdir(tmp) if compression_off: tar = tarfile.TarFile.open(name=outfile_base, mode='w:') else: tar = tarfile.TarFile.open(name=outfile_base, mode='w:gz') tar.add(infile, recursive=True) if vrt_files: for f in vrt_files.keys(): tar.add(f, recursive=True) tar.close() try: shutil.move(outfile_base, outfile) except shutil.Error as e: grass.fatal(e) os.chdir(olddir) grass.verbose(_("Raster map saved to '%s'" % outfile))
def __del__(self): try_remove(self.histFile)
def main(): filename = options['file'] type = options['type'] vect = options['vect'] e00tmp = str(os.getpid()) #### check for avcimport if not grass.find_program('avcimport'): grass.fatal(_("'avcimport' program not found, install it first") + "\n" + "http://avce00.maptools.org") #### check for e00conv if not grass.find_program('e00conv'): grass.fatal(_("'e00conv' program not found, install it first") + "\n" + "http://avce00.maptools.org") # check that the user didn't use all three, which gets past the parser. if type not in ['point','line','area']: grass.fatal(_('Must specify one of "point", "line", or "area".')) e00name = basename(filename, 'e00') # avcimport only accepts 13 chars: e00shortname = e00name[:13] #check if this is a split E00 file (.e01, .e02 ...): merging = False if os.path.exists(e00name + '.e01') or os.path.exists(e00name + '.E01'): grass.message(_("Found that E00 file is split into pieces (.e01, ...). Merging...")) merging = True if vect: name = vect else: name = e00name ### do import #make a temporary directory tmpdir = grass.tempfile() try_remove(tmpdir) os.mkdir(tmpdir) files = glob.glob(e00name + '.e[0-9][0-9]') + glob.glob(e00name + '.E[0-9][0-9]') for f in files: shutil.copy(f, tmpdir) #change to temporary directory to later avoid removal problems (rm -r ...) os.chdir(tmpdir) #check for binay E00 file (we can just check if import fails): #avcimport doesn't set exist status :-( if merging: files.sort() filename = "%s.cat.%s.e00" % (e00name, e00tmp) outf = file(filename, 'wb') for f in files: inf = file(f, 'rb') shutil.copyfileobj(inf, outf) inf.close() outf.close() nuldev = file(os.devnull, 'w+') grass.message(_("An error may appear next which will be ignored...")) if grass.call(['avcimport', filename, e00shortname], stdout = nuldev, stderr = nuldev) == 1: grass.message(_("E00 ASCII found and converted to Arc Coverage in current directory")) else: grass.message(_("E00 Compressed ASCII found. Will uncompress first...")) try_remove(e00shortname) try_remove(info) grass.call(['e00conv', filename, e00tmp + '.e00']) grass.message(_("...converted to Arc Coverage in current directory")) grass.call(['avcimport', e00tmp + '.e00', e00shortname], stderr = nuldev) #SQL name fix: name = name.replace('-', '_') ## let's import... grass.message(_("Importing %ss...") % type) layer = dict(point = 'LAB', line = 'ARC', area = ['LAB','ARC']) itype = dict(point = 'point', line = 'line', area = 'centroid') if grass.run_command('v.in.ogr', flags = 'o', dsn = e00shortname, layer = layer[type], type = itype[type], output = name) != 0: grass.fatal(_("An error occurred while running v.in.ogr")) grass.message(_("Imported <%s> vector map <%s>.") % (type, name)) #### clean up the mess for root, dirs, files in os.walk('.', False): for f in files: path = os.path.join(root, f) try_remove(path) for d in dirs: path = os.path.join(root, d) try_rmdir(path) os.chdir('..') os.rmdir(tmpdir) #### end grass.message(_("Done.")) # write cmd history: grass.vector_history(name)
def _vnetPathRunAnDone(self, cmd, returncode): """Called when v.net.path analysis is done""" try_remove(self.coordsTmpFile) self._onDone(cmd, returncode)
def tearDownClass(cls): try_remove(cls.correct_file_name_platform_nl) try_remove(cls.correct_file_name_unix_nl) try_remove(cls.wrong_file_name)
def cleanup(): try_remove(tmp)
def cleanup(): for ext in ['', '.sort']: try_remove(tmp + ext)
def main(): fileorig = options['input'] filevect = options['output'] if not filevect: filevect = basename(fileorig, 'txt') #are we in LatLong location? s = grass.read_command("g.proj", flags='j') kv = parse_key_val(s) if kv['+proj'] != 'longlat': grass.fatal(_("This module only operates in LatLong/WGS84 locations")) #### setup temporary file tmpfile = grass.tempfile() coldescs = [("RC", "rc integer"), ("UFI", "uf1 integer"), ("UNI", "uni integer"), ("LAT", "lat double precision"), ("LONG", "lon double precision"), ("DMS_LAT", "dms_lat varchar(6)"), ("DMS_LONG", "dms_long varchar(7)"), ("UTM", "utm varchar(4)"), ("JOG", "jog varchar(7)"), ("FC", "fc varchar(1)"), ("DSG", "dsg varchar(5)"), ("PC", "pc integer"), ("CC1", "cci varchar(2)"), ("ADM1", "adm1 varchar(2)"), ("ADM2", "adm2 varchar(200)"), ("DIM", "dim integer"), ("CC2", "cc2 varchar(2)"), ("NT", "nt varchar(1)"), ("LC", "lc varchar(3)"), ("SHORT_FORM", "shortform varchar(128)"), ("GENERIC", "generic varchar(128)"), ("SORT_NAME", "sortname varchar(200)"), ("FULL_NAME", "fullname varchar(200)"), ("FULL_NAME_ND","funamesd varchar(200)"), ("MODIFY_DATE", "mod_date date")] colnames = [desc[0] for desc in coldescs] coltypes = dict([(desc[0], 'integer' in desc[1]) for desc in coldescs]) header = None num_places = 0 inf = file(fileorig) outf = file(tmpfile, 'wb') for line in inf: fields = line.rstrip('\r\n').split('\t') if not header: header = fields continue vars = dict(zip(header, fields)) fields2 = [] for col in colnames: if col in vars: if coltypes[col] and vars[col] == '': fields2.append('0') else: fields2.append(vars[col]) else: if coltypes[col]: fields2.append('0') else: fields2.append('') line2 = ';'.join(fields2) + '\n' outf.write(line2) num_places += 1 outf.close() inf.close() grass.message(_("Converted %d place names.") % num_places) #TODO: fix dms_lat,dms_long DDMMSS -> DD:MM:SS # Solution: # IN=DDMMSS # DEG=`echo $IN | cut -b1,2` # MIN=`echo $IN | cut -b3,4` # SEC=`echo $IN | cut -b5,6` # DEG_STR="$DEG:$MIN:$SEC" #modifications (to match DBF 10 char column name limit): # short_form -> shortform # sort_name -> sortname # full_name -> fullname # full_name_sd -> funamesd # pump data into GRASS: columns = [desc[1] for desc in coldescs] grass.run_command('v.in.ascii', cat = 0, x = 5, y = 4, sep = ';', input = tmpfile, output = filevect, columns = columns) try_remove(tmpfile) # write cmd history: vgrass.vector_history(filevect)
def Render(self, cmd, env): """If it is needed, download missing WMS data. .. todo:: lmgr deletes mapfile and maskfile when order of layers was changed (drag and drop) - if deleted, fetch data again """ if not haveGdal: return Debug.msg(1, "RenderWMSMgr.Render(%s): force=%d img=%s" % (self.layer, self.layer.forceRender, self.layer.mapfile)) env = copy.copy(env) self.dstSize['cols'] = int(env["GRASS_RENDER_WIDTH"]) self.dstSize['rows'] = int(env["GRASS_RENDER_HEIGHT"]) region = self._getRegionDict(env) self._fitAspect(region, self.dstSize) self.updateMap = True fetchData = True # changed to True when calling Render() zoomChanged = False if self.renderedRegion is None or \ cmd != self.fetched_data_cmd: fetchData = True else: for c in ['north', 'south', 'east', 'west']: if self.renderedRegion and \ region[c] != self.renderedRegion[c]: fetchData = True break for c in ['e-w resol', 'n-s resol']: if self.renderedRegion and \ region[c] != self.renderedRegion[c]: zoomChanged = True break if fetchData: self.fetched_data_cmd = None self.renderedRegion = region try_remove(self.layer.mapfile) try_remove(self.tempMap) self.currentPid = self.thread.GetId() # self.thread.Terminate() self.downloading = True self.fetching_cmd = cmd env["GRASS_RENDER_FILE"] = self.tempMap env["GRASS_REGION"] = self._createRegionStr(region) cmd_render = copy.deepcopy(cmd) cmd_render[1]['quiet'] = True # be quiet self._startTime = time.time() self.thread.Run(callable=self._render, cmd=cmd_render, env=env, ondone=self.OnRenderDone) self.layer.forceRender = False self.updateProgress.emit(layer=self.layer)
def main(): out = options['output'] wfs_url = options['url'] request_base = 'REQUEST=GetFeature&SERVICE=WFS&VERSION=1.0.0' wfs_url += request_base if options['name']: wfs_url += '&TYPENAME=' + options['name'] if options['srs']: wfs_url += '&SRS=' + options['srs'] if options['maximum_features']: wfs_url += '&MAXFEATURES=' + options['maximum_features'] if int(options['maximum_features']) < 1: grass.fatal('Invalid maximum number of features') if options['start_index']: wfs_url += '&STARTINDEX=' + options['start_index'] if int(options['start_index']) < 1: grass.fatal('Features begin with index "1"') if flags['r']: bbox = grass.read_command("g.region", flags = 'w').split('=')[1] wfs_url += '&BBOX=' + bbox if flags['l']: wfs_url = options['url'] + 'REQUEST=GetCapabilities&SERVICE=WFS&VERSION=1.0.0' tmp = grass.tempfile() tmpxml = tmp + '.xml' grass.debug(wfs_url) grass.message(_("Retrieving data...")) inf = urllib.urlopen(wfs_url) outf = file(tmpxml, 'wb') while True: s = inf.read() if not s: break outf.write(s) inf.close() outf.close() if flags['l']: import shutil if os.path.exists('wms_capabilities.xml'): grass.fatal('A file called "wms_capabilities.xml" already exists here') # os.move() might fail if the temp file is on another volume, so we copy instead shutil.copy(tmpxml, 'wms_capabilities.xml') try_remove(tmpxml) sys.exit(0) grass.message(_("Importing data...")) ret = grass.run_command('v.in.ogr', flags = 'o', dsn = tmpxml, out = out) try_remove(tmpxml) if ret == 0: grass.message(_("Vector points map <%s> imported from WFS.") % out) else: grass.message(_("WFS import failed"))
def cleanup(): try_remove(tmp) for f in glob.glob(tmp + '_*'): try_remove(f)
def __del__(self): try_remove(self.tempMap)
def main(): layers = options["map"].split(",") if len(layers) < 2: gcore.error(_("At least 2 maps are required")) tmpfile = gcore.tempfile() for map in layers: if not gcore.find_file(map, element="cell")["file"]: gcore.fatal(_("Raster map <%s> not found") % map) gcore.write_command("d.text", color="black", size=4, line=1, stdin="CORRELATION") os.environ["GRASS_RENDER_FILE_READ"] = "TRUE" colors = "red black blue green gray violet".split() line = 2 iloop = 0 jloop = 0 for iloop, i in enumerate(layers): for jloop, j in enumerate(layers): if i != j and iloop <= jloop: color = colors[0] colors = colors[1:] colors.append(color) gcore.write_command("d.text", color=color, size=4, line=line, stdin="%s %s" % (i, j)) line += 1 ofile = file(tmpfile, "w") gcore.run_command("r.stats", flags="cnA", input=(i, j), stdout=ofile) ofile.close() ifile = file(tmpfile, "r") first = True for l in ifile: f = l.rstrip("\r\n").split(" ") x = float(f[0]) y = float(f[1]) if first: minx = maxx = x miny = maxy = y first = False if minx > x: minx = x if maxx < x: maxx = x if miny > y: miny = y if maxy < y: maxy = y ifile.close() kx = 100.0 / (maxx - minx + 1) ky = 100.0 / (maxy - miny + 1) p = gcore.feed_command("d.graph", color=color) ofile = p.stdin ifile = file(tmpfile, "r") for l in ifile: f = l.rstrip("\r\n").split(" ") x = float(f[0]) y = float(f[1]) ofile.write("icon + 0.1 %f %f\n" % ((x - minx + 1) * kx, (y - miny + 1) * ky)) ifile.close() ofile.close() p.wait() try_remove(tmpfile)
def cleanup(): try_remove(tmp) try_remove(tmp + ".dig")
def main(): out = options["output"] wfs_url = options["url"] request_base = "REQUEST=GetFeature&SERVICE=WFS&VERSION=1.0.0" wfs_url += request_base if options["name"]: wfs_url += "&TYPENAME=" + options["name"] if options["srs"]: wfs_url += "&SRS=" + options["srs"] if options["maximum_features"]: wfs_url += "&MAXFEATURES=" + options["maximum_features"] if int(options["maximum_features"]) < 1: # GTC Invalid WFS maximum features parameter grass.fatal(_("Invalid maximum number of features")) if options["start_index"]: wfs_url += "&STARTINDEX=" + options["start_index"] if int(options["start_index"]) < 1: # GTC Invalid WFS start index parameter grass.fatal(_('Features begin with index "1"')) if flags["r"]: bbox = grass.read_command("g.region", flags="w").split("=")[1] wfs_url += "&BBOX=" + bbox if flags["l"]: wfs_url = options[ "url"] + "REQUEST=GetCapabilities&SERVICE=WFS&VERSION=1.0.0" tmp = grass.tempfile() tmpxml = tmp + ".xml" grass.debug(wfs_url) # Set user and password if given if options["username"] and options["password"]: grass.message(_("Setting username and password...")) if os.path.isfile(options["username"]): with open(options["username"]) as f: filecontent = f.read() user = filecontent.strip() elif options["username"] in os.environ: user = os.environ[options["username"]] else: user = options["username"] if os.path.isfile(options["password"]): with open(options["password"]) as f: filecontent = f.read() pw = filecontent.strip() elif options["password"] in os.environ: pw = os.environ[options["password"]] else: pw = options["password"] passmgr = HTTPPasswordMgrWithDefaultRealm() passmgr.add_password(None, wfs_url, user, pw) authhandler = HTTPBasicAuthHandler(passmgr) opener = build_opener(authhandler) install_opener(opener) # GTC Downloading WFS features grass.message(_("Retrieving data...")) try: inf = urlopen(wfs_url) except HTTPError as e: # GTC WFS request HTTP failure grass.fatal( _("The server couldn't fulfill the request.\nError code: %s") % e.code) except URLError as e: # GTC WFS request network failure grass.fatal(_("Failed to reach the server.\nReason: %s") % e.reason) outf = open(tmpxml, "wb") while True: s = inf.read() if not s: break outf.write(s) inf.close() outf.close() if flags["l"]: import shutil if os.path.exists("wms_capabilities.xml"): grass.fatal( _('A file called "wms_capabilities.xml" already exists here')) # os.move() might fail if the temp file is on another volume, so we copy instead shutil.copy(tmpxml, "wms_capabilities.xml") try_remove(tmpxml) sys.exit(0) grass.message(_("Importing data...")) try: grass.run_command("v.in.ogr", flags="o", input=tmpxml, output=out) grass.message(_("Vector map <%s> imported from WFS.") % out) except: grass.message(_("WFS import failed")) finally: try_remove(tmpxml)