def setUpClass(cls): """Ensures expected computational region and generated data""" cls.use_temp_region() cls.runModule("g.region", n=18, s=0, e=18, w=0, res=6) cls.data_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "data") cls.point_file = os.path.join(cls.data_dir, "points.csv") cls.tmp_dir = TemporaryDirectory() cls.las_file = os.path.join(cls.tmp_dir.name, "points.las") grass.call( [ "pdal", "translate", "-i", cls.point_file, "-o", cls.las_file, "-r", "text", "-w", "las", "--writers.las.format=0", "--writers.las.extra_dims=all", "--writers.las.minor_version=4", ] )
def main(): env = grass.gisenv() mon = env.get('MONITOR', None) if not mon: grass.fatal(_("No monitor selected. Run `d.mon` to select monitor.")) monCmd = env.get('MONITOR_%s_CMDFILE' % mon.upper()) if not monCmd: grass.fatal(_("No cmd file found for monitor <%s>") % mon) try: fd = open(monCmd, 'r') cmdList = fd.readlines() grass.run_command('d.erase') for cmd in cmdList: grass.call(split(cmd)) except IOError as e: grass.fatal(_("Unable to open file '%s' for reading. Details: %s") % \ (monCmd, e)) fd.close() # restore cmd file try: fd = open(monCmd, "w") fd.writelines(cmdList) except IOError as e: grass.fatal(_("Unable to open file '%s' for writing. Details: %s") % \ (monCmd, e)) return 0
def main(): mon = grass.gisenv().get('MONITOR', None) if not mon: grass.fatal(_("No graphics device selected. Use d.mon to select graphics device.")) monCmd = grass.parse_command('d.mon', flags='g').get('cmd', None) if not monCmd or not os.path.isfile(monCmd): grass.fatal(_("Unable to open file '%s'") % monCmd) try: fd = open(monCmd, 'r') cmdList = fd.readlines() grass.run_command('d.erase') for cmd in cmdList: grass.call(split(cmd)) except IOError as e: grass.fatal(_("Unable to open file '%s' for reading. Details: %s") % (monCmd, e)) fd.close() # restore cmd file try: fd = open(monCmd, "w") fd.writelines(cmdList) except IOError as e: grass.fatal(_("Unable to open file '%s' for writing. Details: %s") % (monCmd, e)) return 0
def main(): mon = grass.gisenv().get('MONITOR', None) if not mon: grass.fatal( _("No graphics device selected. Use d.mon to select graphics device." )) monCmd = grass.parse_command('d.mon', flags='g').get('cmd', None) if not monCmd or not os.path.isfile(monCmd): grass.fatal(_("Unable to open file '%s'") % monCmd) try: fd = open(monCmd, 'r') cmdList = fd.readlines() grass.run_command('d.erase') for cmd in cmdList: grass.call(split(cmd)) except IOError as e: grass.fatal(_("Unable to open file '%s' for reading. Details: %s") % \ (monCmd, e)) fd.close() # restore cmd file try: fd = open(monCmd, "w") fd.writelines(cmdList) except IOError as e: grass.fatal(_("Unable to open file '%s' for writing. Details: %s") % \ (monCmd, e)) return 0
def draw_gnuplot(what, xlabels, output, img_format, coord_legend): xrange = 0 for i, row in enumerate(what): outfile = os.path.join(tmp_dir, 'data_%d' % i) outf = open(outfile, 'w') xrange = max(xrange, len(row) - 2) for j, val in enumerate(row[3:]): outf.write("%d %s\n" % (j + 1, val)) outf.close() # build gnuplot script lines = [] if output: if img_format == 'png': term_opts = "png truecolor large size 825,550" elif img_format == 'eps': term_opts = "postscript eps color solid size 6,4" elif img_format == 'svg': term_opts = "svg size 825,550 dynamic solid" else: gcore.fatal(_("Programmer error (%s)") % img_format) lines += ["set term " + term_opts, "set output '%s'" % output] lines += [ "set xtics (%s)" % xlabels, "set grid", "set title 'Spectral signatures'", "set xrange [0.5 : %d - 0.5]" % xrange, "set noclabel", "set xlabel 'Bands'", "set xtics rotate by -40", "set ylabel 'DN Value'", "set style data lines" ] cmd = [] for i, row in enumerate(what): if not coord_legend: title = 'Pick ' + str(i + 1) else: title = str(tuple(row[0:2])) x_datafile = os.path.join(tmp_dir, 'data_%d' % i) cmd.append(" '%s' title '%s'" % (x_datafile, title)) cmd = ','.join(cmd) cmd = ' '.join(['plot', cmd, "with linespoints pt 779"]) lines.append(cmd) plotfile = os.path.join(tmp_dir, 'spectrum.gnuplot') plotf = open(plotfile, 'w') for line in lines: plotf.write(line + '\n') plotf.close() if output: gcore.call(['gnuplot', plotfile]) else: gcore.call(['gnuplot', '-persist', plotfile])
def draw_gnuplot(what, xlabels, output, label): xrange = 0 for i, row in enumerate(what): outfile = 'data_%d' % i outf = file(outfile, 'w') xrange = max(xrange, len(row) - 2) for j, val in enumerate(row[3:]): outf.write("%d %s\n" % (j + 1, val)) outf.close() # build gnuplot script lines = [] if output: lines += [ "set term png large", "set output '%s'" % output ] lines += [ "set xtics (%s)" % xlabels, "set grid", "set title 'Spectral signatures'", "set xrange [0:%d]" % xrange, "set noclabel", "set xlabel 'Bands'", "set ylabel 'DN Value'", "set style data lines" ] cmd = [] for i, row in enumerate(what): if not label: title = str(i + 1) else: title = str(tuple(row[0:2])) cmd.append("'data_%d' title '%s'" % (i, title)) cmd = ','.join(cmd) cmd = ' '.join(['plot', cmd, "with linespoints pt 779"]) lines.append(cmd) plotfile = 'spectrum.gnuplot' plotf = file(plotfile, 'w') for line in lines: plotf.write(line + '\n') plotf.close() if output: grass.call(['gnuplot', plotfile]) else: grass.call(['gnuplot', '-persist', plotfile])
def main(): env = grass.gisenv() mon = env.get("MONITOR", None) if not mon: grass.fatal(_("No monitor selected. Run `d.mon` to select monitor.")) monCmd = env.get("MONITOR_%s_CMDFILE" % mon) if not monCmd: grass.fatal(_("No cmd file found for monitor <%s>") % mon) try: fd = open(monCmd, "r") cmdList = fd.readlines() grass.run_command("d.erase") for cmd in cmdList: grass.call(split(cmd)) except IOError, e: grass.fatal(_("Unable to open file '%s' for reading. Details: %s") % (monCmd, e))
def main(): test_file = options['test'] expected = grass.tempfile() result = grass.tempfile() dbconn = grassdb.db_connection() grass.message(_("Using DB driver: %s") % dbconn['driver']) infile = os.path.join(os.environ['GISBASE'], 'etc', 'db.test', test_file) inf = file(infile) while True: type = inf.readline() if not type: break type = type.rstrip('\r\n') sql = inf.readline().rstrip('\r\n') sys.stdout.write(sql + '\n') # Copy expected result to temp file try: if type == 'X': grass.write_command('db.execute', input='-', stdin=sql + '\n') else: resf = file(result, 'w') grass.write_command('db.select', input='-', flags='c', stdin=sql + '\n', stdout=resf) resf.close() except CalledModuleError: grass.error("EXECUTE: ******** ERROR ********") else: grass.message(_("EXECUTE: OK")) expf = file(expected, 'w') while True: res = inf.readline().rstrip('\r\n') if not res: break expf.write(res + '\n') expf.close() if type == 'S': if grass.call(['diff', result, expected]) != 0: grass.error("RESULT: ******** ERROR ********") else: grass.message(_("RESULT: OK"))
def main(): test_file = options["test"] expected = gcore.tempfile() result = gcore.tempfile() dbconn = grassdb.db_connection() gcore.message(_("Using DB driver: %s") % dbconn["driver"]) infile = os.path.join(os.environ["GISBASE"], "etc", "db.test", test_file) inf = open(infile) while True: type = inf.readline() if not type: break type = type.rstrip("\r\n") sql = inf.readline().rstrip("\r\n") sys.stdout.write(sql + "\n") # Copy expected result to temp file try: if type == "X": gcore.write_command("db.execute", input="-", stdin=sql + "\n") else: resf = open(result, "w") gcore.write_command("db.select", input="-", flags="c", stdin=sql + "\n", stdout=resf) resf.close() except CalledModuleError: gcore.error("EXECUTE: ******** ERROR ********") else: gcore.message(_("EXECUTE: OK")) expf = open(expected, "w") while True: res = inf.readline().rstrip("\r\n") if not res: break expf.write(res + "\n") expf.close() if type == "S": if gcore.call(["diff", result, expected]) != 0: gcore.error("RESULT: ******** ERROR ********") else: gcore.message(_("RESULT: OK"))
def main(argv=None): if argv is None: argv = sys.argv if len(argv) > 1 and argv[1] == "-d": printDiff = True else: printDiff = False if len(argv) > 1 and argv[1] == "-h": print(sys.stderr, __doc__, file=sys.stderr) return 1 nuldev = open(os.devnull, "w+") grass.info("Step 1: running make...") grass.call(["make"], stderr=nuldev) grass.info("Step 2: parsing modules...") modules = dict() modules = parseModules() grass.info("Step 3: reading menu data...") data = LayerManagerMenuData() grass.info("Step 4: updating menu data...") updateData(data, modules) if printDiff: tempFile = tempfile.NamedTemporaryFile() grass.info("Step 5: diff menu data...") writeData(data, tempFile.name) grass.call( ["diff", "-u", os.path.join("xml", "menudata.xml"), tempFile.name], stderr=nuldev, ) else: grass.info("Step 5: writing menu data (menudata.xml)...") writeData(data) return 0
def main(): mon = grass.gisenv().get("MONITOR", None) if not mon: grass.fatal( _("No graphics device selected. Use d.mon to select graphics device." )) monCmd = grass.parse_command("d.mon", flags="g").get("cmd", None) if not monCmd or not os.path.isfile(monCmd): grass.fatal(_("Unable to open file '%s'") % monCmd) try: fd = open(monCmd, "r") cmdList = fd.readlines() grass.run_command("d.erase") for cmd in cmdList: if cmd.startswith("#"): continue grass.call(split(cmd)) except IOError as e: grass.fatal( _("Unable to open file '%s' for reading. Details: %s") % (monCmd, e)) fd.close() # restore cmd file try: fd = open(monCmd, "w") fd.writelines(cmdList) except IOError as e: grass.fatal( _("Unable to open file '%s' for writing. Details: %s") % (monCmd, e)) return 0
def main(argv=None): if argv is None: argv = sys.argv if len(argv) > 1 and argv[1] == '-d': printDiff = True else: printDiff = False if len(argv) > 1 and argv[1] == '-h': print >> sys.stderr, __doc__ return 1 nuldev = file(os.devnull, 'w+') grass.info("Step 1: running make...") grass.call(['make'], stderr=nuldev) grass.info("Step 2: parsing modules...") modules = dict() modules = parseModules() grass.info("Step 3: reading menu data...") data = LayerManagerMenuData() grass.info("Step 4: updating menu data...") updateData(data, modules) if printDiff: tempFile = tempfile.NamedTemporaryFile() grass.info("Step 5: diff menu data...") writeData(data, tempFile.name) grass.call(['diff', '-u', os.path.join('xml', 'menudata.xml'), tempFile.name], stderr=nuldev) else: grass.info("Step 5: writing menu data (menudata.xml)...") writeData(data) return 0
def main(argv=None): if argv is None: argv = sys.argv if len(argv) > 1 and argv[1] == '-d': printDiff = True else: printDiff = False if len(argv) > 1 and argv[1] == '-h': print(sys.stderr, __doc__, file=sys.stderr) return 1 nuldev = file(os.devnull, 'w+') grass.info("Step 1: running make...") grass.call(['make'], stderr=nuldev) grass.info("Step 2: parsing modules...") modules = dict() modules = parseModules() grass.info("Step 3: reading menu data...") data = LayerManagerMenuData() grass.info("Step 4: updating menu data...") updateData(data, modules) if printDiff: tempFile = tempfile.NamedTemporaryFile() grass.info("Step 5: diff menu data...") writeData(data, tempFile.name) grass.call(['diff', '-u', os.path.join('xml', 'menudata.xml'), tempFile.name], stderr=nuldev) else: grass.info("Step 5: writing menu data (menudata.xml)...") writeData(data) return 0
def main(): test_file = options['test'] expected = grass.tempfile() result = grass.tempfile() dbconn = grassdb.db_connection() grass.message(_("Using DB driver: %s") % dbconn['driver']) infile = os.path.join(os.environ['GISBASE'], 'etc', 'db.test', test_file) inf = file(infile) while True: type = inf.readline() if not type: break type = type.rstrip('\r\n') sql = inf.readline().rstrip('\r\n') sys.stdout.write(sql + '\n') # Copy expected result to temp file try: if type == 'X': grass.write_command('db.execute', input = '-', stdin = sql + '\n') else: resf = file(result, 'w') grass.write_command('db.select', input = '-', flags = 'c', stdin = sql + '\n', stdout = resf) resf.close() except CalledModuleError: grass.error("EXECUTE: ******** ERROR ********") else: grass.message(_("EXECUTE: OK")) expf = file(expected, 'w') while True: res = inf.readline().rstrip('\r\n') if not res: break expf.write(res + '\n') expf.close() if type == 'S': if grass.call(['diff', result, expected]) != 0: grass.error("RESULT: ******** ERROR ********") else: grass.message(_("RESULT: OK"))
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 main(): handler = options["handler"] if options["tempfile"]: img_tmp = options["tempfile"] # TODO: add option for GRASS_RENDER_FILE_COMPRESSION=0,1-9 else: img_tmp = grass.tempfile() os.remove(img_tmp) img_tmp += ".bmp" if flags["b"]: print('GRASS_RENDER_FILE="%s"' % img_tmp) if "GRASS_RENDER_WIDTH" not in os.environ: print("GRASS_RENDER_WIDTH=%s" % options["width"]) if "GRASS_RENDER_HEIGHT" not in os.environ: print("GRASS_RENDER_HEIGHT=%s" % options["height"]) if flags["c"]: print("GRASS_RENDER_IMMEDIATE=cairo") else: print("GRASS_RENDER_IMMEDIATE=PNG") print("GRASS_RENDER_FILE_MAPPED=TRUE") print("GRASS_RENDER_FILE_READ=TRUE") print( "export GRASS_RENDER_FILE GRASS_RENDER_WIDTH GRASS_RENDER_HEIGHT GRASS_RENDER_IMMEDIATE GRASS_RENDER_FILE_MAPPED GRASS_RENDER_FILE_READ;" ) print("d.erase bgcolor=%s;" % options["color"]) if handler == "none": grass.message("Image file is '%s'" % img_tmp) elif handler == "qiv": print('qiv -e -T "%s" &' % img_tmp) # add --center ? else: print('%s image="%s" percent=%s &' % (handler, img_tmp, options["percent"])) sys.exit(0) if flags["d"]: print("rem DOS export not yet implemented") sys.exit(0) ## rest of this won't work, as parent can't inherit from the child.. ## (unless we do some ugly g.gisenv) ## ... any ideas? end by running grass.call(['bash'])? if not grass.find_program(handler, "--help"): grass.fatal(_("'%s' not found.") % handler) os.environ["GRASS_RENDER_FILE"] = img_tmp if "GRASS_RENDER_WIDTH" not in os.environ: os.environ["GRASS_RENDER_WIDTH"] = options["width"] if "GRASS_RENDER_HEIGHT" not in os.environ: os.environ["GRASS_RENDER_HEIGHT"] = options["height"] if flags["c"]: os.environ["GRASS_RENDER_IMMEDIATE"] = "cairo" os.environ["GRASS_RENDER_FILE_MAPPED"] = "TRUE" os.environ["GRASS_RENDER_FILE_READ"] = "TRUE" # ? os.environ['GRASS_PNG_AUTO_WRITE'] = 'FALSE' grass.run_command("d.erase", bgcolor=options["color"]) if handler == "qiv": ret = grass.call(["qiv", "-e", "-T", img_tmp]) else: ret = grass.exec_command(handler, image=img_tmp, percent=options["percent"]) os.remove(img_tmp) sys.exit(ret)
def install_extension_other(): gisbase = os.getenv('GISBASE') gui_list = list_wxgui_extensions(print_module = False) if options['extension'] not in gui_list: classchar = options['extension'].split('.', 1)[0] moduleclass = expand_module_class_name(classchar) url = options['svnurl'] + '/' + moduleclass + '/' + options['extension'] else: url = options['svnurl'] + '/gui/wxpython/' + options['extension'] if not flags['s']: grass.fatal(_("Installation of wxGUI extension requires -%s flag.") % 's') grass.message(_("Fetching <%s> from GRASS-Addons SVN (be patient)...") % options['extension']) os.chdir(tmpdir) if grass.verbosity() <= 2: outdev = open(os.devnull, 'w') else: outdev = sys.stdout if grass.call(['svn', 'checkout', url], stdout = outdev) != 0: grass.fatal(_("GRASS Addons <%s> not found") % options['extension']) dirs = { 'bin' : os.path.join(tmpdir, options['extension'], 'bin'), 'docs' : os.path.join(tmpdir, options['extension'], 'docs'), 'html' : os.path.join(tmpdir, options['extension'], 'docs', 'html'), 'man' : os.path.join(tmpdir, options['extension'], 'man'), 'man1' : os.path.join(tmpdir, options['extension'], 'man', 'man1'), 'scripts' : os.path.join(tmpdir, options['extension'], 'scripts'), 'etc' : os.path.join(tmpdir, options['extension'], 'etc'), } makeCmd = ['make', 'MODULE_TOPDIR=%s' % gisbase.replace(' ', '\ '), 'ARCH_BINDIR=%s' % dirs['bin'], 'BIN=%s' % dirs['bin'], 'HTMLDIR=%s' % dirs['html'], 'MANDIR=%s' % dirs['man1'], 'SCRIPTDIR=%s' % dirs['scripts'], 'ETC=%s' % os.path.join(dirs['etc'],options['extension']) ] installCmd = ['make', 'MODULE_TOPDIR=%s' % gisbase, 'ARCH_DISTDIR=%s' % os.path.join(tmpdir, options['extension']), 'INST_DIR=%s' % options['prefix'], 'install' ] if flags['d']: grass.message(_("To compile run:")) sys.stderr.write(' '.join(makeCmd) + '\n') grass.message(_("To install run:\n\n")) sys.stderr.write(' '.join(installCmd) + '\n') return os.chdir(os.path.join(tmpdir, options['extension'])) grass.message(_("Compiling...")) if options['extension'] not in gui_list: ret = grass.call(makeCmd, stdout = outdev) else: ret = grass.call(['make', 'MODULE_TOPDIR=%s' % gisbase.replace(' ', '\ ')], stdout = outdev) if ret != 0: grass.fatal(_('Compilation failed, sorry. Please check above error messages.')) if flags['i'] or options['extension'] in gui_list: return grass.message(_("Installing...")) return grass.call(installCmd, stdout = outdev)
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 = grass.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() grass.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...")) grass.try_remove(e00shortname) grass.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) grass.try_remove(path) for d in dirs: path = os.path.join(root, d) grass.try_rmdir(path) os.chdir('..') os.rmdir(tmpdir) #### end grass.message(_("Done.")) # write cmd history: grass.vector_history(name)
def main(): handler = options['handler'] if options['tempfile']: img_tmp = options['tempfile'] #TODO: add option for GRASS_RENDER_FILE_COMPRESSION=0,1-9 else: img_tmp = grass.tempfile() os.remove(img_tmp) img_tmp += ".bmp" if flags['b']: print('GRASS_RENDER_FILE="%s"' % img_tmp) if not os.environ.has_key("GRASS_RENDER_WIDTH"): print('GRASS_RENDER_WIDTH=%s' % options['width']) if not os.environ.has_key("GRASS_RENDER_HEIGHT"): print('GRASS_RENDER_HEIGHT=%s' % options['height']) if flags['c']: print('GRASS_RENDER_IMMEDIATE=cairo') else: print('GRASS_RENDER_IMMEDIATE=PNG') print('GRASS_RENDER_FILE_MAPPED=TRUE') print('GRASS_RENDER_FILE_READ=TRUE') print( 'export GRASS_RENDER_FILE GRASS_RENDER_WIDTH GRASS_RENDER_HEIGHT GRASS_RENDER_IMMEDIATE GRASS_RENDER_FILE_MAPPED GRASS_RENDER_FILE_READ;' ) print('d.erase bgcolor=%s;' % options['color']) if handler == "none": grass.message("Image file is '%s'" % img_tmp) elif handler == "qiv": print('qiv -e -T "%s" &' % img_tmp) # add --center ? else: print('%s image="%s" percent=%s &' % (handler, img_tmp, options['percent'])) sys.exit(0) if flags['d']: print('rem DOS export not yet implemented') sys.exit(0) ## rest of this won't work, as parent can't inherit from the child.. ## (unless we do some ugly g.gisenv) ## ... any ideas? end by running grass.call(['bash'])? if not grass.find_program(handler, '--help'): grass.fatal(_("'%s' not found.") % handler) os.environ['GRASS_RENDER_FILE'] = img_tmp if not os.environ.has_key("GRASS_RENDER_WIDTH"): os.environ['GRASS_RENDER_WIDTH'] = options['width'] if not os.environ.has_key("GRASS_RENDER_HEIGHT"): os.environ['GRASS_RENDER_HEIGHT'] = options['height'] if flags['c']: os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo' os.environ['GRASS_RENDER_FILE_MAPPED'] = 'TRUE' os.environ['GRASS_RENDER_FILE_READ'] = 'TRUE' #? os.environ['GRASS_PNG_AUTO_WRITE'] = 'FALSE' grass.run_command('d.erase', bgcolor=options['color']) if handler == "qiv": ret = grass.call(['qiv', '-e', '-T', img_tmp]) else: ret = grass.exec_command(handler, image=img_tmp, percent=options['percent']) os.remove(img_tmp) sys.exit(ret)
def install_extension_other(name): gisbase = os.getenv('GISBASE') classchar = name.split('.', 1)[0] moduleclass = expand_module_class_name(classchar) url = options['svnurl'] + '/' + moduleclass + '/' + name grass.message(_("Fetching <%s> from GRASS-Addons SVN repository (be patient)...") % name) os.chdir(TMPDIR) if grass.verbosity() <= 2: outdev = open(os.devnull, 'w') else: outdev = sys.stdout if grass.call(['svn', 'checkout', url], stdout = outdev) != 0: grass.fatal(_("GRASS Addons <%s> not found") % name) dirs = { 'bin' : os.path.join(TMPDIR, name, 'bin'), 'docs' : os.path.join(TMPDIR, name, 'docs'), 'html' : os.path.join(TMPDIR, name, 'docs', 'html'), 'rest' : os.path.join(TMPDIR, name, 'docs', 'rest'), 'man' : os.path.join(TMPDIR, name, 'docs', 'man', 'man1'), 'script' : os.path.join(TMPDIR, name, 'scripts'), ### TODO: handle locales also for addons # 'string' : os.path.join(TMPDIR, name, 'locale'), 'string' : os.path.join(TMPDIR, name), 'etc' : os.path.join(TMPDIR, name, 'etc'), } makeCmd = ['make', 'MODULE_TOPDIR=%s' % gisbase.replace(' ', '\ '), 'RUN_GISRC=%s' % os.environ['GISRC'], 'BIN=%s' % dirs['bin'], 'HTMLDIR=%s' % dirs['html'], 'RESTDIR=%s' % dirs['rest'], 'MANDIR=%s' % dirs['man'], 'SCRIPTDIR=%s' % dirs['script'], 'STRINGDIR=%s' % dirs['string'], 'ETC=%s' % os.path.join(dirs['etc'], name) ] installCmd = ['make', 'MODULE_TOPDIR=%s' % gisbase, 'ARCH_DISTDIR=%s' % os.path.join(TMPDIR, name), 'INST_DIR=%s' % options['prefix'], 'install' ] if flags['d']: grass.message("\n%s\n" % _("To compile run:")) sys.stderr.write(' '.join(makeCmd) + '\n') grass.message("\n%s\n" % _("To install run:")) sys.stderr.write(' '.join(installCmd) + '\n') return 0 os.chdir(os.path.join(TMPDIR, name)) grass.message(_("Compiling...")) if 0 != grass.call(makeCmd, stdout = outdev): grass.fatal(_('Compilation failed, sorry. Please check above error messages.')) if flags['i']: return 0 grass.message(_("Installing...")) return grass.call(installCmd, stdout = outdev)
def install_extension(): gisbase = os.getenv('GISBASE') if not gisbase: grass.fatal(_('$GISBASE not defined')) if grass.find_program(options['extension'], ['--help']): grass.warning(_("Extension '%s' already installed. Will be updated...") % options['extension']) gui_list = list_wxgui_extensions(print_module = False) if options['extension'] not in gui_list: classchar = options['extension'].split('.', 1)[0] moduleclass = expand_module_class_name(classchar) url = options['svnurl'] + '/' + moduleclass + '/' + options['extension'] else: url = options['svnurl'] + '/gui/wxpython/' + options['extension'] if not flags['s']: grass.fatal(_("Installation of wxGUI extension requires -%s flag.") % 's') grass.message(_("Fetching '%s' from GRASS-Addons SVN (be patient)...") % options['extension']) os.chdir(tmpdir) if grass.verbosity() == 0: outdev = open(os.devnull, 'w') else: outdev = sys.stdout if grass.call(['svn', 'checkout', url], stdout = outdev) != 0: grass.fatal(_("GRASS Addons '%s' not found in repository") % options['extension']) dirs = { 'bin' : os.path.join(tmpdir, options['extension'], 'bin'), 'docs' : os.path.join(tmpdir, options['extension'], 'docs'), 'html' : os.path.join(tmpdir, options['extension'], 'docs', 'html'), 'man' : os.path.join(tmpdir, options['extension'], 'man'), 'man1' : os.path.join(tmpdir, options['extension'], 'man', 'man1'), 'scripts' : os.path.join(tmpdir, options['extension'], 'scripts'), 'etc' : os.path.join(tmpdir, options['extension'], 'etc'), } makeCmd = ['make', 'MODULE_TOPDIR=%s' % gisbase.replace(' ', '\ '), 'BIN=%s' % dirs['bin'], 'HTMLDIR=%s' % dirs['html'], 'MANDIR=%s' % dirs['man1'], 'SCRIPTDIR=%s' % dirs['scripts'], 'ETC=%s' % dirs['etc'] ] installCmd = ['make', 'MODULE_TOPDIR=%s' % gisbase, 'ARCH_DISTDIR=%s' % os.path.join(tmpdir, options['extension']), 'INST_DIR=%s' % options['prefix'], 'install' ] if flags['d']: grass.message(_("To compile run:")) sys.stderr.write(' '.join(makeCmd) + '\n') grass.message(_("To install run:\n\n")) sys.stderr.write(' '.join(installCmd) + '\n') return os.chdir(os.path.join(tmpdir, options['extension'])) grass.message(_("Compiling '%s'...") % options['extension']) if options['extension'] not in gui_list: for d in dirs.itervalues(): if not os.path.exists(d): os.makedirs(d) ret = grass.call(makeCmd, stdout = outdev) else: ret = grass.call(['make', 'MODULE_TOPDIR=%s' % gisbase.replace(' ', '\ ')], stdout = outdev) if ret != 0: grass.fatal(_('Compilation failed, sorry. Please check above error messages.')) if flags['i'] or options['extension'] in gui_list: return grass.message(_("Installing '%s'...") % options['extension']) ret = grass.call(installCmd, stdout = outdev) if ret != 0: grass.warning(_('Installation failed, sorry. Please check above error messages.')) else: grass.message(_("Installation of '%s' successfully finished.") % options['extension']) # manual page: fix href if os.getenv('GRASS_ADDON_PATH'): html_man = os.path.join(os.getenv('GRASS_ADDON_PATH'), 'docs', 'html', options['extension'] + '.html') if os.path.exists(html_man): fd = open(html_man) html_str = '\n'.join(fd.readlines()) fd.close() for rep in ('grassdocs.css', 'grass_logo.png'): patt = re.compile(rep, re.IGNORECASE) html_str = patt.sub(os.path.join(gisbase, 'docs', 'html', rep), html_str) patt = re.compile(r'(<a href=")(d|db|g|i|m|p|ps|r|r3|s|v|wxGUI)(\.)(.+)(.html">)', re.IGNORECASE) while True: m = patt.search(html_str) if not m: break html_str = patt.sub(m.group(1) + os.path.join(gisbase, 'docs', 'html', m.group(2) + m.group(3) + m.group(4)) + m.group(5), html_str, count = 1) fd = open(html_man, "w") fd.write(html_str) fd.close() if not os.environ.has_key('GRASS_ADDON_PATH') or \ not os.environ['GRASS_ADDON_PATH']: grass.warning(_('This add-on module will not function until you set the ' 'GRASS_ADDON_PATH environment variable (see "g.manual variables")'))
for layer in self.overlays: if force or layer.force_render: layer.Render() if __name__ == "__main__": import gettext gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode=True) Map = Map() Map.GetRegion(update=True) Map.AddLayer(type="raster", name="elevation", command=["d.rast", "map=elevation@PERMANENT"], l_opacity=.7) Map.AddLayer(type="vector", name="roadsmajor", command=[ "d.vect", "map=roadsmajor@PERMANENT", "color=red", "width=3", "type=line" ]) image = Map.Render(force=True) if image: grass.call(["display", image])
def ReverseListOfLayers(self): """!Reverse list of layers""" return self.layers.reverse() def RenderOverlays(self, force): """!Render overlays only (for nviz)""" for layer in self.overlays: if force or layer.force_render: layer.Render() if __name__ == "__main__": import gettext gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True) Map = Map() Map.GetRegion(update = True) Map.AddLayer(type = "raster", name = "elevation", command = ["d.rast", "map=elevation@PERMANENT"], l_opacity = .7) Map.AddLayer(type = "vector", name = "roadsmajor", command = ["d.vect", "map=roadsmajor@PERMANENT", "color=red", "width=3", "type=line"]) image = Map.Render(force = True) if image: grass.call(["display", image])
def draw_gnuplot(what, xlabels, output, img_format, coord_legend): xrange = 0 for i, row in enumerate(what): outfile = os.path.join(tmp_dir, 'data_%d' % i) outf = open(outfile, 'w') xrange = max(xrange, len(row) - 2) for j, val in enumerate(row[3:]): outf.write("%d %s\n" % (j + 1, val)) outf.close() # build gnuplot script lines = [] if output: if img_format == 'png': term_opts = "png truecolor large size 825,550" elif img_format == 'eps': term_opts = "postscript eps color solid size 6,4" elif img_format == 'svg': term_opts = "svg size 825,550 dynamic solid" else: grass.fatal(_("Programmer error (%s)") % img_format) lines += [ "set term " + term_opts, "set output '%s'" % output ] lines += [ "set xtics (%s)" % xlabels, "set grid", "set title 'Spectral signatures'", "set xrange [0.5 : %d - 0.5]" % xrange, "set noclabel", "set xlabel 'Bands'", "set xtics rotate by -40", "set ylabel 'DN Value'", "set style data lines" ] cmd = [] for i, row in enumerate(what): if not coord_legend: title = 'Pick ' + str(i + 1) else: title = str(tuple(row[0:2])) x_datafile = os.path.join(tmp_dir, 'data_%d' % i) cmd.append(" '%s' title '%s'" % (x_datafile, title)) cmd = ','.join(cmd) cmd = ' '.join(['plot', cmd, "with linespoints pt 779"]) lines.append(cmd) plotfile = os.path.join(tmp_dir, 'spectrum.gnuplot') plotf = open(plotfile, 'w') for line in lines: plotf.write(line + '\n') plotf.close() if output: grass.call(['gnuplot', plotfile]) else: grass.call(['gnuplot', '-persist', plotfile])
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)