def main(options, flags): url = options['url'] name = options['name'] database = options['dbase'] if not database: # use current database = gs.gisenv()['GISDBASE'] if not name: name = location_name_from_url(url) destination = os.path.join(database, name) if os.path.exists(destination): gs.fatal( _("Location named <%s> already exists," " download canceled") % name) return gs.message(_("Downloading and extracting...")) directory = download_end_extract(url) if not is_location_valid(directory): try_rmdir(directory) gs.message(_("Finalizing...")) shutil.copytree(src=directory, dst=destination) try_rmdir(directory) gs.message(_("Location is now in %s") % destination)
def cleanup(): # see end of main() grass.verbose(_("Module cleanup in: "+TMPDIR)) os.system('rm '+ os.path.join( TMPDIR, '*')) if REMOVETMPDIR: try_rmdir(TMPDIR) else: grass.message("\n%s\n" % _("printws: Temp dir remove failed. Do it yourself, please:")) sys.stderr.write('%s\n' % TMPDIR % ' <---- this')
def cleanup(): # see end of main() grass.verbose(_("Module cleanup in: " + TMPDIR)) os.system('rm ' + os.path.join(TMPDIR, '*')) if REMOVETMPDIR: try_rmdir(TMPDIR) else: grass.message( "\n%s\n" % _("printws: Temp dir remove failed. Do it yourself, please:")) sys.stderr.write('%s\n' % TMPDIR % ' <---- this')
def clean_temp(pid): """Remove temporary files of the current processes :param pid: Process ID whos tempfiles to remove :type pid: int """ from pathlib import Path from shutil import rmtree tempfile = Path(grass.tempfile(create=False)) for path in tempfile.parent.glob(str(pid) + ".*"): if path.is_file(): grassutils.try_rmdir(path) else: rmtree(path)
def download_location(url, name, database): """Wrapper to return DownloadError by value It also moves the location directory to the database. """ try: # TODO: the unpacking could go right to the path (but less # robust) or replace copytree here with move directory = download_and_extract(source=url) destination = os.path.join(database, name) if not is_location_valid(directory): return _("Downloaded location is not valid") shutil.copytree(src=directory, dst=destination) try_rmdir(directory) except DownloadError as error: return error return None
def main(options, unused_flags): """Download and copy location to destination""" url = options["url"] name = options["name"] database = options["path"] if not database: # Use the current database path. database = gs.gisenv()["GISDBASE"] if not name: name = location_name_from_url(url) destination = Path(database) / name if destination.exists(): gs.fatal( _("Location named <{}> already exists, download canceled").format( name)) gs.message(_("Downloading and extracting...")) try: directory = download_and_extract(url) if not directory.is_dir(): gs.fatal( _("Archive contains only one file and no mapset directories")) atexit.register(lambda: try_rmdir(directory)) except DownloadError as error: gs.fatal(_("Unable to get the location: {error}").format(error=error)) if not is_location_valid(directory): gs.verbose(_("Searching for valid location...")) # This in fact deal with location being on the third level of directories # thanks to how the extraction functions work (leaving out one level). result = find_location_in_directory(directory, recurse=1) if result: # We just want to show relative path in the message. # The relative path misses the root directory (name), because we # loose it on the way. (We should use parent directory to get the # full relative path, but the directory name is diffrent now. # This is the consequence of how the extract functions work.) relative = os.path.relpath(result, start=directory) gs.verbose( _("Location found in a nested directory '{directory}'").format( directory=relative)) directory = result else: # The list is similarly misleading as the relative path above # as it misses the root directory, but it still should be useful. files_and_dirs = os.listdir(directory) gs.fatal( _("The dowloaded file is not a valid GRASS Location." " The extracted file contains these files and directories:" "\n{files_and_dirs}").format( files_and_dirs=" ".join(files_and_dirs))) gs.verbose(_("Copying to final destination...")) shutil.copytree(src=directory, dst=destination) gs.message(_("Path to the location now <{path}>").format(path=destination))
def cleanup(): try_rmdir(tmp_dir)
def cleanup(): try_rmdir(tmp)
def cleanup(): try_rmdir(basedir)
def main(): # Following declarations MAY will used in future for sure. global GISDBASE, LAYERCOUNT, LASTFILE # Check if ImageMagick is available since it is essential if os.name == 'nt': if grass.find_program('magick', '-version'): grass.verbose(_('printws: ImageMagick is available: OK!')) else: grass.fatal( 'ImageMagick is not accessible. See documentation of m.printws module for details.' ) else: if grass.find_program('convert', '-version'): grass.verbose(_('printws: ImageMagick is available: OK!')) else: grass.fatal( 'ImageMagick is not accessible. See documentation of m.printws module for details.' ) textmacros = {} # %nam% macros are kept for backward compatibility textmacros['%TIME24%'] = time.strftime("%H:%M:%S") textmacros['%DATEYMD%'] = time.strftime("%Y.%m.%d") textmacros['%DATEMDY%'] = time.strftime("%m/%d/%Y") if not hasPwd: textmacros['%USERNAME%'] = '(user unknown)' else: textmacros['%USERNAME%'] = pwd.getpwuid(os.getuid())[0] # using $ for macros in the future. New items should be created # exclusively as $macros later on textmacros['\$TIME24'] = textmacros['%TIME24%'] textmacros['\$DATEYMD'] = textmacros['%DATEYMD%'] textmacros['\$DATEMDY'] = textmacros['%DATEMDY%'] textmacros['\$USERNAME'] = textmacros['%USERNAME%'] textmacros[ '\$SPC'] = u'\u00A0' #?? d.text won't display this at string end hmmm # saves region for restoring at end # doing with official method: grass.use_temp_region() # getting/setting screen/print dpi ratio if len(options['dpi']) > 0: dpioption = float(options['dpi']) else: dpioption = 150.0 if len(options['screendpi']) > 0: screendpioption = float(options['screendpi']) else: screendpioption = 100.0 global UPSIZE UPSIZE = float(dpioption) / float(screendpioption) if len(options['input']) > 0: displays = readworkspace(options['input']) else: quit() textmacros['%GXW%'] = options['input'] textmacros['\$GXW'] = textmacros['%GXW%'] displaycounter = 0 # there could be multiple displays in a workspace so we loop them # each display is a whole and independent file assembly for key in displays: textmacros['%DISPLAY%'] = key textmacros['\$DISPLAY'] = key grass.verbose(_('printws: rendering display: ' + key)) displaycounter = displaycounter + 1 layers = copy.deepcopy(displays[key]) # extracting extent information from layers dic and erase the item # extents[0-5] w s e n minz maxz ; extents [6-9] window x y w h extents = layers[0] grass.verbose("m.printws: EXTENTS from workspace:" + str(extents)) # was debug message del layers[0] regionmode = '' if len(options['region']) > 0: grass.run_command("g.region", region=options['region']) regionmode = 'region' else: grass.run_command("g.region", "", w=extents[0], s=extents[1], e=extents[2], n=extents[3]) regionmode = 'window' # setting GRASS rendering environment # dummy file name is defined since the following lines # when switching on the cairo driver would create # an empty map.png in the current directory os.environ['GRASS_RENDER_FILE'] = os.path.join( TMPDIR, str(os.getpid()) + '_DIS_' + str(00) + '_GEN_' + str(00) + '.png') os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo' os.environ['GRASS_RENDER_FILE_READ'] = 'TRUE' os.environ['GRASS_RENDER_TRANSPARENT'] = 'TRUE' os.environ['GRASS_RENDER_FILE_COMPRESSION'] = '0' os.environ['GRASS_RENDER_FILE_MAPPED'] = 'TRUE' # reading further options and setting defaults if len(options['page']) > 0: pageoption = options['page'] else: pageoption = 'A4landscape' # parsing titles, etc. if len(options['font']) > 0: isAsterisk = options['font'].find('*') if isAsterisk > 0: titlefont = getfontbypattern(options['font'].replace('*', '')) else: titlefont = options['font'] else: titlefont = getfontbypattern('Open') # try to find something UTF-8 grass.verbose(_("printws: titlefont: " + titlefont)) if len(options['titlecolor']) > 0: titlecolor = options['titlecolor'] else: titlecolor = black if len(options['maintitlesize']) > 0: maintitlesize = converttommfrom(float(options['maintitlesize']), options['layunits']) else: maintitlesize = 10.0 if len(options['subtitlesize']) > 0: subtitlesize = converttommfrom(float(options['subtitlesize']), options['layunits']) else: subtitlesize = 7.0 if len(options['pssize']) > 0: pssize = converttommfrom(float(options['pssize']), options['layunits']) else: pssize = 5.0 # Please fasten your seatbelts :) Calculations start here. # ------------------------------------------------------------------- pagesizes = getpagesizes(pageoption) pagesizesindots = dictodots(pagesizes, dpioption) # Leave space for titles up and ps down - still in mm !! upperspace = 0 subtitletop = 0 titletop = 0 if len(options['maintitle']) > 0: titletop = 0.4 * maintitlesize upperspace = upperspace + titletop + maintitlesize if len(options['subtitle']) > 0: subtitletop = upperspace + 0.4 * subtitlesize upperspace = subtitletop + subtitlesize + 1 lowerspace = 0 if (len(options['psundercentral']) > 0) or (len( options['psunderright']) > 0) or (len(options['psunderleft']) > 0): lowerspace = lowerspace + pssize + 2 os.environ['GRASS_RENDER_WIDTH'] = str(pagesizesindots['w']) os.environ['GRASS_RENDER_HEIGHT'] = str(pagesizesindots['h']) pagemargins = getpagemargins(options['pagemargin'], options['layunits']) pagemarginsindots = dictodots(pagemargins, dpioption) # Getting max drawing area in dots mxfd = getmaxframeindots(pagemarginsindots, pagesizesindots) maxframe = str(mxfd['t']) + ',' + str(mxfd['b']) + \ ',' + str(mxfd['l']) + ',' + str(mxfd['r']) # convert font size in mm to percentage for d.text mxfmm = dictomm(mxfd, dpioption) maintitlesize = float(maintitlesize) / (mxfmm['b'] - mxfmm['t']) * 100.0 subtitlesize = float(subtitlesize) / (mxfmm['b'] - mxfmm['t']) * 100.0 pssize = float(pssize) / (mxfmm['r'] - mxfmm['l']) * 100.0 # subtitle location is another issue subtitletoppercent = 100.0 - subtitletop / \ (mxfmm['b'] - mxfmm['t']) * 100.0 titletoppercent = 100.0 - titletop / \ (mxfmm['b'] - mxfmm['t']) * 100.0 mapul = getmapUL(options['mapupperleft'], options['layunits']) mapulindots = dictodots(mapul, dpioption) mapsizes = getmapsizes(options['mapsize'], options['layunits']) mapsizesindots = dictodots(mapsizes, dpioption) # Correcting map area ratio to ratio of region edges # OR screen window edges depeding on "regionmode" # for later: grass.use_temp_region() ISLATLONG = False s = grass.read_command("g.region", flags='p') kv = grass.parse_key_val(s, sep=':') regioncols = float(kv['cols'].strip()) regionrows = float(kv['rows'].strip()) ewrestemp = kv['ewres'].strip() nsrestemp = kv['nsres'].strip() if ewrestemp.find(':') > 0: ISLATLONG = True ewrestemp = ewrestemp.split(':') ewres = float(ewrestemp[0]) + float(ewrestemp[1]) / 60.0 + float( ewrestemp[2]) / 3600.0 nsrestemp = nsrestemp.split(':') nsres = float(nsrestemp[0]) + float(nsrestemp[1]) / 60.0 + float( nsrestemp[2]) / 3600.0 else: ewres = float(ewrestemp) nsres = float(nsrestemp) sizex = regioncols * ewres sizey = regionrows * nsres grass.verbose(_("printws: sizex " + str(sizex))) grass.verbose(_("printws: sizey " + str(sizey))) if regionmode == 'region': hregionratio = float(sizex) / float(sizey) grass.verbose(_("printws: REGION MODE -> region ")) else: # surprisingly doing the SAME # using screen window ratio for map area # next line was a test for this but didn't help on gadgets positioning #hregionratio = float(extents[8]) / float(extents[9]) hregionratio = float(sizex) / float(sizey) grass.verbose(_("printws: REGION MODE -> window")) hmapratio = mapsizes['w'] / mapsizes['h'] grass.verbose(_("printws: raw mapsizes: " + str(mapsizesindots))) grass.verbose(_("printws: hr: " + str(hregionratio))) grass.verbose(_("printws: hm: " + str(hmapratio))) if hregionratio > hmapratio: grass.verbose( _("printws: Map area height correction / " + str(hregionratio))) mapsizes['h'] = mapsizes['w'] / hregionratio elif hregionratio < hmapratio: grass.verbose( _("printws: Map area width correction * " + str(hregionratio))) mapsizes['w'] = mapsizes['h'] * hregionratio mapsizesindots = dictodots(mapsizes, dpioption) # changing region resolution to match print resolution # to eliminate unnecessary CPU heating/data transfer # so as to make it faster # with only invisible detail loss. colsregiontomap = float(mapsizesindots['w']) / regioncols rowsregiontomap = float(mapsizesindots['h']) / regionrows newewres = ewres newnsres = nsres # if colsregiontomap < 1: # CHANGE: also enables raising of resolution to prevent # pixelation because of low resolution setting... newewres = ewres / colsregiontomap # if rowsregiontomap < 1: newnsres = nsres / rowsregiontomap # WOW - no necessary to convert back to DMS for nsres / ewres #if ISLATLONG: # newewresstr=decdeg2dms(newewres) # newnsresstr=decdeg2dms(newnsres) #else: newewresstr = str(newewres) newnsresstr = str(newnsres) grass.run_command("g.region", ewres=newewresstr, nsres=newnsresstr) # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # it seems that d.wms uses the GRASS_REGION from region info # others may also do so we set it # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! kv2 = {} kv2['e'] = kv['east'] kv2['n'] = kv['north'] kv2['s'] = kv['south'] kv2['w'] = kv['west'] kv2['ewres'] = newewresstr kv2['nsres'] = newnsresstr #kv2['rows'] #- autocalculated to resolution - no need to set explicitly #kv2['cols'] #- autocalculated to resolution - no need to set explicitly #grass.message(str(kv2)) #grass.message(grass.region_env(**kv2)) #grass.message(s) os.environ['GRASS_REGION'] = grass.region_env(**kv2) # Getting mapping area in dots # Correcting mxfd to leave space for title and subscript pagemarginstitles = copy.deepcopy(pagemargins) pagemarginstitles['t'] = pagemarginstitles['t'] + upperspace pagemarginstitles['b'] = pagemarginstitles['b'] + lowerspace pagemarginsindotstitles = dictodots(pagemarginstitles, dpioption) mxfdtitles = getmaxframeindots(pagemarginsindotstitles, pagesizesindots) mpfd = getmapframeindots(mapulindots, mapsizesindots, mxfdtitles) if pageoption == 'Flexi': # For 'Flexi' page we modify the setup to create # a page containing only the map without margins grass.verbose(_("printws: pre Flexi mapframe: " + str(mpfd))) mpfd['b'] = mpfd['b'] - mpfd['t'] mpfd['t'] = 0 mpfd['r'] = mpfd['r'] - mpfd['l'] mpfd['l'] = 0 os.environ['GRASS_RENDER_WIDTH'] = str(mpfd['r']) os.environ['GRASS_RENDER_HEIGHT'] = str(mpfd['b']) grass.verbose(_("printws: post Flexi mapframe: " + str(mpfd))) mapframe = str(mpfd['t']) + ',' + str(mpfd['b']) + \ ',' + str(mpfd['l']) + ',' + str(mpfd['r']) grass.verbose(_("printws: DOT VALUES ARE:")) grass.verbose(_("printws: maxframe: " + str(mxfd))) grass.verbose(_("printws: maxframe: " + maxframe)) grass.verbose(_("printws: mapframe: " + str(mpfd))) grass.verbose(_("printws: mapframe: " + mapframe)) grass.verbose(_("printws: page: " + str(pagesizesindots))) grass.verbose(_("printws: margins: " + str(pagemarginsindots))) grass.verbose(_("printws: mapUL: " + str(mapulindots))) grass.verbose( _("printws: mapsizes (corrected): " + str(mapsizesindots))) grass.verbose(_("printws: ewres (corrected): " + str(newewres))) grass.verbose(_("printws: nsres (corrected): " + str(newnsres))) # quit() # ------------------- INMAP ------------------- # Do not limit -map. It was: -limit map 720000000 before... # So we can grow on disk as long as it lasts imcommand = 'convert -limit memory 720000000 -units PixelsPerInch -density ' + \ str(int(dpioption)) + ' ' if os.name == 'nt': imcommand = 'magick ' + imcommand os.environ['GRASS_RENDER_FRAME'] = mapframe grass.verbose(_("printws: Rendering: the following layers: ")) lastopacity = '-1' for lay in layers: grass.verbose(_(lay[1] + ' at: ' + lay[0] + ' opacity')) if lay[0] == '1': if lastopacity <> '1': LASTFILE = os.path.join(TMPDIR, str(os.getpid()) + \ '_DIS_' + str(displaycounter) + '_GEN_' + \ str(LAYERCOUNT) + '.' + TMPFORMAT) os.environ['GRASS_RENDER_FILE'] = LASTFILE LAYERCOUNT = LAYERCOUNT + 2 imcommand = imcommand + ' ' + LASTFILE lastopacity = '1' render(lay[1], lay[2], lay[3]) else: lastopacity = lay[0] LASTFILE = os.path.join( TMPDIR, str(os.getpid()) + '_DIS_' + str(displaycounter) + '_GEN_' + str(LAYERCOUNT) + '.' + TMPFORMAT) LAYERCOUNT = LAYERCOUNT + 2 os.environ['GRASS_RENDER_FILE'] = LASTFILE grass.verbose("LAY: " + str(lay)) render(lay[1], lay[2], lay[3]) imcommand = imcommand + \ ' \( ' + LASTFILE + ' -channel a -evaluate multiply ' + \ lay[0] + ' +channel \)' # setting resolution back to pre-script state since map rendering is # finished # CHANGE: not necessary anymore since we use temp_region now # However, since we did set GRASS_REGION, let's redo it here os.environ.pop('GRASS_REGION') # ------------------- OUTSIDE MAP texts, etc ------------------- if pageoption == 'Flexi': grass.verbose( _('m.printws: WARNING! Felxi mode, will not create titles, etc...' )) else: os.environ['GRASS_RENDER_FRAME'] = maxframe dict = {} dict['task'] = "d.text" dict['color'] = titlecolor dict['font'] = titlefont dict['charset'] = "UTF-8" if len(options['maintitle']) > 1: dict['text'] = decodetextmacros(options['maintitle'], textmacros) dict['at'] = "50," + str(titletoppercent) dict['align'] = "uc" dict['size'] = str(maintitlesize) render(str(dict), dict, {}) if len(options['subtitle']) > 1: dict['text'] = decodetextmacros(options['subtitle'], textmacros) dict['at'] = "50," + str(subtitletoppercent) dict['align'] = "uc" dict['size'] = str(subtitlesize) render(str(dict), dict, {}) dict['size'] = str(pssize) if len(options['psundercentral']) > 1: dict['text'] = decodetextmacros(options['psundercentral'], textmacros) dict['at'] = "50,1" dict['align'] = "lc" render(str(dict), dict, {}) if len(options['psunderleft']) > 1: dict['text'] = decodetextmacros(options['psunderleft'], textmacros) dict['at'] = "0,1" dict['align'] = "ll" render(str(dict), dict, {}) if len(options['psunderright']) > 1: dict['text'] = decodetextmacros(options['psunderright'], textmacros) dict['at'] = "100,1" dict['align'] = "lr" render(str(dict), dict, {}) # ------------------- GENERATING OUTPUT FILE ------------------- if len(options['output']) > 1: output = options['output'] else: output = 'map_' + str(os.getpid()) # remove extension AND display number and naming if any output = os.path.splitext(output)[0] output = re.sub('_DISPLAY_[0-9]+_.*', '', output) if len(options['format']) > 1: extension = options['format'] else: extension = 'pdf' displaypart = '' if len(displays) > 1: displaypart = '_DISPLAY_' + str(displaycounter) + '_' + key pagedata = getpagedata(pageoption) #params= ' -extent '+str(pagesizesindots['w'])+'x'+str(pagesizesindots['h'])+' -gravity center -compress jpeg -page '+pagedata['page']+' '+pagedata['parameters']+' -units PixelsPerInch -density '+str(dpioption)+'x'+str(dpioption)+' ' params = ' -compress jpeg -quality 92 ' + \ pagedata['parameters'] + ' -units PixelsPerInch -density ' + \ str(int(dpioption)) + ' ' imcommand = imcommand + ' -layers flatten ' + params + \ '"' + output + displaypart + '.' + extension + '"' grass.verbose( _('printws: And the imagemagick command is... ' + imcommand)) os.system(imcommand) if not flags['d']: grass.verbose(_('printws: Doing graceful cleanup...')) os.system('rm ' + os.path.join(TMPDIR, str(os.getpid()) + '*_GEN_*')) if REMOVE_TMPDIR: try_rmdir(TMPDIR) else: grass.message( "\n%s\n" % _("printws: Temp dir remove failed. Do it yourself, please:")) sys.stderr.write('%s\n' % TMPDIR % ' <---- this') # restoring pre-script region # - not necessary as we are using grass.use_temp_region() in the future return 0
def main(): filename = options['input'] type = options['type'] vect = options['output'] e00tmp = str(os.getpid()) # check for avcimport if not gcore.find_program('avcimport'): gcore.fatal( _("'avcimport' program not found, install it first") + "\n" + "http://avce00.maptools.org") # check for e00conv if not gcore.find_program('e00conv'): gcore.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']: gcore.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'): gcore.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 = gcore.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+') gcore.message(_("An error may appear next which will be ignored...")) if gcore.call(['avcimport', filename, e00shortname], stdout=nuldev, stderr=nuldev) == 1: gcore.message( _("E00 ASCII found and converted to Arc Coverage in " "current directory")) else: gcore.message( _("E00 Compressed ASCII found. Will uncompress first...")) try_remove(e00shortname) gcore.call(['e00conv', filename, e00tmp + '.e00']) gcore.message(_("...converted to Arc Coverage in current directory")) gcore.call(['avcimport', e00tmp + '.e00', e00shortname], stderr=nuldev) # SQL name fix: name = name.replace('-', '_') # let's import... gcore.message(_("Importing %ss...") % type) layer = dict(point='LAB', line='ARC', area=['LAB', 'ARC']) itype = dict(point='point', line='line', area='centroid') try: gcore.run_command('v.in.ogr', flags='o', input=e00shortname, layer=layer[type], type=itype[type], output=name) except CalledModuleError: gcore.fatal(_("An error occurred while running v.in.ogr")) gcore.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 gcore.message(_("Done.")) # write cmd history: gvect.vector_history(name)
def cleanup(): if REMOVE_TMPDIR: try_rmdir(TMPDIR) else: grass.message("\n%s\n" % _("Path to the source code:")) sys.stderr.write('%s\n' % os.path.join(TMPDIR, options['extension']))
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 main(): filename = options["input"] type = options["type"] vect = options["output"] e00tmp = str(os.getpid()) # check for avcimport if not gcore.find_program("avcimport"): gcore.fatal(_("'avcimport' program not found, install it first") + "\n" + "http://avce00.maptools.org") # check for e00conv if not gcore.find_program("e00conv"): gcore.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"]: gcore.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"): gcore.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 = gcore.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+") gcore.message(_("An error may appear next which will be ignored...")) if gcore.call(["avcimport", filename, e00shortname], stdout=nuldev, stderr=nuldev) == 1: gcore.message(_("E00 ASCII found and converted to Arc Coverage in " "current directory")) else: gcore.message(_("E00 Compressed ASCII found. Will uncompress first...")) try_remove(e00shortname) gcore.call(["e00conv", filename, e00tmp + ".e00"]) gcore.message(_("...converted to Arc Coverage in current directory")) gcore.call(["avcimport", e00tmp + ".e00", e00shortname], stderr=nuldev) # SQL name fix: name = name.replace("-", "_") # let's import... gcore.message(_("Importing %ss...") % type) layer = dict(point="LAB", line="ARC", area=["LAB", "ARC"]) itype = dict(point="point", line="line", area="centroid") try: gcore.run_command("v.in.ogr", flags="o", input=e00shortname, layer=layer[type], type=itype[type], output=name) except CalledModuleError: gcore.fatal(_("An error occurred while running v.in.ogr")) gcore.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 gcore.message(_("Done.")) # write cmd history: gvect.vector_history(name)