core.py 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  1. """!@package grass.script.core
  2. @brief GRASS Python scripting module (core functions)
  3. Core functions to be used in Python scripts.
  4. Usage:
  5. @code
  6. from grass.script import core as grass
  7. grass.parser()
  8. ...
  9. @endcode
  10. (C) 2008-2010 by the GRASS Development Team
  11. This program is free software under the GNU General Public
  12. License (>=v2). Read the file COPYING that comes with GRASS
  13. for details.
  14. @author Glynn Clements
  15. @author Martin Landa <landa.martin gmail.com>
  16. @author Michael Barton <michael.barton@asu.edu>
  17. """
  18. import os
  19. import sys
  20. import types
  21. import re
  22. import atexit
  23. import subprocess
  24. import shutil
  25. # i18N
  26. import gettext
  27. gettext.install('grasslibs', os.path.join(os.getenv("GISBASE"), 'locale'), unicode=True)
  28. # subprocess wrapper that uses shell on Windows
  29. class Popen(subprocess.Popen):
  30. def __init__(self, args, bufsize=0, executable=None,
  31. stdin=None, stdout=None, stderr=None,
  32. preexec_fn=None, close_fds=False, shell=None,
  33. cwd=None, env=None, universal_newlines=False,
  34. startupinfo=None, creationflags=0):
  35. if shell == None:
  36. shell = (sys.platform == "win32")
  37. subprocess.Popen.__init__(self, args, bufsize, executable,
  38. stdin, stdout, stderr,
  39. preexec_fn, close_fds, shell,
  40. cwd, env, universal_newlines,
  41. startupinfo, creationflags)
  42. PIPE = subprocess.PIPE
  43. STDOUT = subprocess.STDOUT
  44. class ScriptException(Exception):
  45. def __init__(self, msg):
  46. self.value = msg
  47. def __str__(self):
  48. return repr(self.value)
  49. raise_on_error = False # raise exception instead of calling fatal()
  50. debug_level = 0 # DEBUG level
  51. def call(*args, **kwargs):
  52. return Popen(*args, **kwargs).wait()
  53. # GRASS-oriented interface to subprocess module
  54. _popen_args = ["bufsize", "executable", "stdin", "stdout", "stderr",
  55. "preexec_fn", "close_fds", "cwd", "env",
  56. "universal_newlines", "startupinfo", "creationflags"]
  57. def _make_val(val):
  58. if isinstance(val, types.StringType) or \
  59. isinstance(val, types.UnicodeType):
  60. return val
  61. if isinstance(val, types.ListType):
  62. return ",".join(map(_make_val, val))
  63. if isinstance(val, types.TupleType):
  64. return _make_val(list(val))
  65. return str(val)
  66. def make_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, **options):
  67. """!Return a list of strings suitable for use as the args parameter to
  68. Popen() or call(). Example:
  69. @code
  70. >>> grass.make_command("g.message", flags = 'w', message = 'this is a warning')
  71. ['g.message', '-w', 'message=this is a warning']
  72. @endcode
  73. @param prog GRASS module
  74. @param flags flags to be used (given as a string)
  75. @param overwrite True to enable overwriting the output (<tt>--o</tt>)
  76. @param quiet True to run quietly (<tt>--q</tt>)
  77. @param verbose True to run verbosely (<tt>--v</tt>)
  78. @param options module's parameters
  79. @return list of arguments
  80. """
  81. args = [prog]
  82. if overwrite:
  83. args.append("--o")
  84. if quiet:
  85. args.append("--q")
  86. if verbose:
  87. args.append("--v")
  88. if flags:
  89. args.append("-%s" % flags)
  90. for opt, val in options.iteritems():
  91. if val != None:
  92. if opt[0] == '_':
  93. opt = opt[1:]
  94. args.append("%s=%s" % (opt, _make_val(val)))
  95. return args
  96. def start_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, **kwargs):
  97. """!Returns a Popen object with the command created by make_command.
  98. Accepts any of the arguments which Popen() accepts apart from "args"
  99. and "shell".
  100. \code
  101. >>> p = grass.start_command("g.gisenv", stdout = subprocess.PIPE)
  102. >>> print p
  103. <subprocess.Popen object at 0xb7c12f6c>
  104. >>> print p.communicate()[0]
  105. GISDBASE='/opt/grass-data';
  106. LOCATION_NAME='spearfish60';
  107. MAPSET='glynn';
  108. GRASS_DB_ENCODING='ascii';
  109. GRASS_GUI='text';
  110. MONITOR='x0';
  111. \endcode
  112. @param prog GRASS module
  113. @param flags flags to be used (given as a string)
  114. @param overwrite True to enable overwriting the output (<tt>--o</tt>)
  115. @param quiet True to run quietly (<tt>--q</tt>)
  116. @param verbose True to run verbosely (<tt>--v</tt>)
  117. @param kwargs module's parameters
  118. @return Popen object
  119. """
  120. options = {}
  121. popts = {}
  122. for opt, val in kwargs.iteritems():
  123. if opt in _popen_args:
  124. popts[opt] = val
  125. else:
  126. options[opt] = val
  127. args = make_command(prog, flags, overwrite, quiet, verbose, **options)
  128. global debug_level
  129. if debug_level > 0:
  130. sys.stderr.write("D1/%d: %s.start_command(): %s\n" % (debug_level, __name__, ' '.join(args)))
  131. sys.stderr.flush()
  132. return Popen(args, **popts)
  133. def run_command(*args, **kwargs):
  134. """!Passes all arguments to start_command(), then waits for the process to
  135. complete, returning its exit code. Similar to subprocess.call(), but
  136. with the make_command() interface.
  137. @param args list of unnamed arguments (see start_command() for details)
  138. @param kwargs list of named arguments (see start_command() for details)
  139. @return exit code (0 for success)
  140. """
  141. ps = start_command(*args, **kwargs)
  142. return ps.wait()
  143. def pipe_command(*args, **kwargs):
  144. """!Passes all arguments to start_command(), but also adds
  145. "stdout = PIPE". Returns the Popen object.
  146. \code
  147. >>> p = grass.pipe_command("g.gisenv")
  148. >>> print p
  149. <subprocess.Popen object at 0xb7c12f6c>
  150. >>> print p.communicate()[0]
  151. GISDBASE='/opt/grass-data';
  152. LOCATION_NAME='spearfish60';
  153. MAPSET='glynn';
  154. GRASS_DB_ENCODING='ascii';
  155. GRASS_GUI='text';
  156. MONITOR='x0';
  157. \endcode
  158. @param args list of unnamed arguments (see start_command() for details)
  159. @param kwargs list of named arguments (see start_command() for details)
  160. @return Popen object
  161. """
  162. kwargs['stdout'] = PIPE
  163. return start_command(*args, **kwargs)
  164. def feed_command(*args, **kwargs):
  165. """!Passes all arguments to start_command(), but also adds
  166. "stdin = PIPE". Returns the Popen object.
  167. @param args list of unnamed arguments (see start_command() for details)
  168. @param kwargs list of named arguments (see start_command() for details)
  169. @return Popen object
  170. """
  171. kwargs['stdin'] = PIPE
  172. return start_command(*args, **kwargs)
  173. def read_command(*args, **kwargs):
  174. """!Passes all arguments to pipe_command, then waits for the process to
  175. complete, returning its stdout (i.e. similar to shell `backticks`).
  176. @param args list of unnamed arguments (see start_command() for details)
  177. @param kwargs list of named arguments (see start_command() for details)
  178. @return stdout
  179. """
  180. ps = pipe_command(*args, **kwargs)
  181. return ps.communicate()[0]
  182. def parse_command(*args, **kwargs):
  183. """!Passes all arguments to read_command, then parses the output by
  184. parse_key_val().
  185. Parsing function can be optionally given by <b>parse</b> parameter
  186. including its arguments, e.g.
  187. @code
  188. parse_command(..., parse = (grass.parse_key_val, { 'sep' : ':' }))
  189. @endcode
  190. @param args list of unnamed arguments (see start_command() for details)
  191. @param kwargs list of named arguments (see start_command() for details)
  192. @return parsed module output
  193. """
  194. parse = None
  195. if kwargs.has_key('parse'):
  196. if type(kwargs['parse']) is types.TupleType:
  197. parse = kwargs['parse'][0]
  198. parse_args = kwargs['parse'][1]
  199. del kwargs['parse']
  200. if not parse:
  201. parse = parse_key_val # use default fn
  202. parse_args = {}
  203. res = read_command(*args, **kwargs)
  204. return parse(res, **parse_args)
  205. def write_command(*args, **kwargs):
  206. """!Passes all arguments to feed_command, with the string specified
  207. by the 'stdin' argument fed to the process' stdin.
  208. @param args list of unnamed arguments (see start_command() for details)
  209. @param kwargs list of named arguments (see start_command() for details)
  210. @return return code
  211. """
  212. stdin = kwargs['stdin']
  213. p = feed_command(*args, **kwargs)
  214. p.stdin.write(stdin)
  215. p.stdin.close()
  216. return p.wait()
  217. def exec_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, env = None, **kwargs):
  218. """!Interface to os.execvpe(), but with the make_command() interface.
  219. @param prog GRASS module
  220. @param flags flags to be used (given as a string)
  221. @param overwrite True to enable overwriting the output (<tt>--o</tt>)
  222. @param quiet True to run quietly (<tt>--q</tt>)
  223. @param verbose True to run verbosely (<tt>--v</tt>)
  224. @param env directory with enviromental variables
  225. @param kwargs module's parameters
  226. """
  227. args = make_command(prog, flags, overwrite, quiet, verbose, **kwargs)
  228. if env == None:
  229. env = os.environ
  230. os.execvpe(prog, args, env)
  231. # interface to g.message
  232. def message(msg, flag = None):
  233. """!Display a message using `g.message`
  234. @param msg message to be displayed
  235. @param flag flags (given as string)
  236. """
  237. run_command("g.message", flags = flag, message = msg)
  238. def debug(msg, debug = 1):
  239. """!Display a debugging message using `g.message -d`
  240. @param msg debugging message to be displayed
  241. @param debug debug level (0-5)
  242. """
  243. run_command("g.message", flags = 'd', message = msg, debug = debug)
  244. def verbose(msg):
  245. """!Display a verbose message using `g.message -v`
  246. @param msg verbose message to be displayed
  247. """
  248. message(msg, flag = 'v')
  249. def info(msg):
  250. """!Display an informational message using `g.message -i`
  251. @param msg informational message to be displayed
  252. """
  253. message(msg, flag = 'i')
  254. def percent(i, n, s):
  255. """!Display a progress info message using `g.message -p`
  256. @code
  257. message(_("Percent complete..."))
  258. n = 100
  259. for i in range(n):
  260. percent(i, n, 1)
  261. percent(1, 1, 1)
  262. @endcode
  263. @param i current item
  264. @param n total number of items
  265. @param s increment size
  266. """
  267. message("%d %d %d" % (i, n, s), flag = 'p')
  268. def warning(msg):
  269. """!Display a warning message using `g.message -w`
  270. @param msg warning message to be displayed
  271. """
  272. message(msg, flag = 'w')
  273. def error(msg):
  274. """!Display an error message using `g.message -e`
  275. Raise exception when on_error is 'raise'.
  276. @param msg error message to be displayed
  277. """
  278. global raise_on_error
  279. if raise_on_error:
  280. raise ScriptException(msg)
  281. else:
  282. message(msg, flag = 'e')
  283. def fatal(msg):
  284. """!Display an error message using `g.message -e`, then abort
  285. @param msg error message to be displayed
  286. """
  287. error(msg)
  288. sys.exit(1)
  289. def set_raise_on_error(raise_exp = True):
  290. """!Define behaviour on error (error() called)
  291. @param raise_exp True to raise ScriptException instead of calling
  292. error()
  293. @return current status
  294. """
  295. global raise_on_error
  296. tmp_raise = raise_on_error
  297. raise_on_error = raise_exp
  298. # interface to g.parser
  299. def _parse_opts(lines):
  300. options = {}
  301. flags = {}
  302. for line in lines:
  303. line = line.rstrip('\r\n')
  304. if not line:
  305. break
  306. try:
  307. [var, val] = line.split('=', 1)
  308. except:
  309. raise SyntaxError("invalid output from g.parser: %s" % line)
  310. if var.startswith('flag_'):
  311. flags[var[5:]] = bool(int(val))
  312. elif var.startswith('opt_'):
  313. options[var[4:]] = val
  314. elif var in ['GRASS_OVERWRITE', 'GRASS_VERBOSE']:
  315. os.environ[var] = val
  316. else:
  317. raise SyntaxError("invalid output from g.parser: %s" % line)
  318. return (options, flags)
  319. def parser():
  320. """!Interface to g.parser, intended to be run from the top-level, e.g.:
  321. @code
  322. if __name__ == "__main__":
  323. options, flags = grass.parser()
  324. main()
  325. @endcode
  326. Thereafter, the global variables "options" and "flags" will be
  327. dictionaries containing option/flag values, keyed by lower-case
  328. option/flag names. The values in "options" are strings, those in
  329. "flags" are Python booleans.
  330. """
  331. if not os.getenv("GISBASE"):
  332. print >> sys.stderr, "You must be in GRASS GIS to run this program."
  333. sys.exit(1)
  334. cmdline = [basename(sys.argv[0])]
  335. cmdline += ['"' + arg + '"' for arg in sys.argv[1:]]
  336. os.environ['CMDLINE'] = ' '.join(cmdline)
  337. argv = sys.argv[:]
  338. name = argv[0]
  339. if not os.path.isabs(name):
  340. if os.sep in name or (os.altsep and os.altsep in name):
  341. argv[0] = os.path.abspath(name)
  342. else:
  343. argv[0] = os.path.join(sys.path[0], name)
  344. p = Popen(['g.parser', '-s'] + argv, stdout = PIPE)
  345. s = p.communicate()[0]
  346. lines = s.splitlines()
  347. if not lines or lines[0].rstrip('\r\n') != "@ARGS_PARSED@":
  348. sys.stdout.write(s)
  349. sys.exit(1)
  350. return _parse_opts(lines[1:])
  351. # interface to g.tempfile
  352. def tempfile():
  353. """!Returns the name of a temporary file, created with g.tempfile."""
  354. return read_command("g.tempfile", pid = os.getpid()).strip()
  355. def tempdir():
  356. """!Returns the name of a temporary dir, created with g.tempfile."""
  357. tmp = read_command("g.tempfile", pid = os.getpid()).strip()
  358. try_remove(tmp)
  359. os.mkdir(tmp)
  360. return tmp
  361. # key-value parsers
  362. def parse_key_val(s, sep = '=', dflt = None, val_type = None, vsep = None):
  363. """!Parse a string into a dictionary, where entries are separated
  364. by newlines and the key and value are separated by `sep' (default: `=')
  365. @param s string to be parsed
  366. @param sep key/value separator
  367. @param dflt default value to be used
  368. @param val_type value type (None for no cast)
  369. @param vsep vertical separator (default os.linesep)
  370. @return parsed input (dictionary of keys/values)
  371. """
  372. result = {}
  373. if not s:
  374. return result
  375. if vsep:
  376. lines = s.split(vsep)
  377. try:
  378. lines.remove('\n')
  379. except ValueError:
  380. pass
  381. else:
  382. lines = s.splitlines()
  383. for line in lines:
  384. kv = line.split(sep, 1)
  385. k = kv[0].strip()
  386. if len(kv) > 1:
  387. v = kv[1]
  388. else:
  389. v = dflt
  390. if val_type:
  391. result[k] = val_type(v)
  392. else:
  393. result[k] = v
  394. return result
  395. # interface to g.gisenv
  396. def gisenv():
  397. """!Returns the output from running g.gisenv (with no arguments), as a
  398. dictionary. Example:
  399. \code
  400. >>> env = grass.gisenv()
  401. >>> print env['GISDBASE']
  402. /opt/grass-data
  403. \endcode
  404. @return list of GRASS variables
  405. """
  406. s = read_command("g.gisenv", flags='n')
  407. return parse_key_val(s)
  408. # interface to g.region
  409. def region():
  410. """!Returns the output from running "g.region -g", as a
  411. dictionary. Example:
  412. \code
  413. >>> region = grass.region()
  414. >>> [region[key] for key in "nsew"]
  415. [228500.0, 215000.0, 645000.0, 630000.0]
  416. >>> (region['nsres'], region['ewres'])
  417. (10.0, 10.0)
  418. \endcode
  419. @return dictionary of region values
  420. """
  421. s = read_command("g.region", flags='g')
  422. reg = parse_key_val(s, val_type = float)
  423. for k in ['rows', 'cols']:
  424. reg[k] = int(reg[k])
  425. return reg
  426. def use_temp_region():
  427. """!Copies the current region to a temporary region with "g.region save=",
  428. then sets WIND_OVERRIDE to refer to that region. Installs an atexit
  429. handler to delete the temporary region upon termination.
  430. """
  431. name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
  432. run_command("g.region", save = name)
  433. os.environ['WIND_OVERRIDE'] = name
  434. atexit.register(del_temp_region)
  435. def del_temp_region():
  436. """!Unsets WIND_OVERRIDE and removes any region named by it."""
  437. try:
  438. name = os.environ.pop('WIND_OVERRIDE')
  439. run_command("g.remove", quiet = True, region = name)
  440. except:
  441. pass
  442. # interface to g.findfile
  443. def find_file(name, element = 'cell', mapset = None):
  444. """!Returns the output from running g.findfile as a
  445. dictionary. Example:
  446. \code
  447. >>> result = grass.find_file('fields', element = 'vector')
  448. >>> print result['fullname']
  449. fields@PERMANENT
  450. >>> print result['file']
  451. /opt/grass-data/spearfish60/PERMANENT/vector/fields
  452. \endcode
  453. @param name file name
  454. @param element element type (default 'cell')
  455. @param mapset mapset name (default all mapsets in search path)
  456. @return parsed output of g.findfile
  457. """
  458. s = read_command("g.findfile", flags='n', element = element, file = name, mapset = mapset)
  459. return parse_key_val(s)
  460. # interface to g.list
  461. def list_grouped(type):
  462. """!List elements grouped by mapsets.
  463. Returns the output from running g.list, as a dictionary where the
  464. keys are mapset names and the values are lists of maps in that
  465. mapset. Example:
  466. @code
  467. >>> grass.list_grouped('rast')['PERMANENT']
  468. ['aspect', 'erosion1', 'quads', 'soils', 'strm.dist', ...
  469. @endcode
  470. @param type element type (rast, vect, rast3d, region, ...)
  471. @return directory of mapsets/elements
  472. """
  473. dashes_re = re.compile("^----+$")
  474. mapset_re = re.compile("<(.*)>")
  475. result = {}
  476. mapset = None
  477. for line in read_command("g.list", type = type).splitlines():
  478. if line == "":
  479. continue
  480. if dashes_re.match(line):
  481. continue
  482. m = mapset_re.search(line)
  483. if m:
  484. mapset = m.group(1)
  485. result[mapset] = []
  486. continue
  487. if mapset:
  488. result[mapset].extend(line.split())
  489. return result
  490. def _concat(xs):
  491. result = []
  492. for x in xs:
  493. result.extend(x)
  494. return result
  495. def list_pairs(type):
  496. """!List of elements as tuples.
  497. Returns the output from running g.list, as a list of (map, mapset)
  498. pairs. Example:
  499. @code
  500. >>> grass.list_pairs('rast')
  501. [('aspect', 'PERMANENT'), ('erosion1', 'PERMANENT'), ('quads', 'PERMANENT'), ...
  502. @endcode
  503. @param type element type (rast, vect, rast3d, region, ...)
  504. @return list of tuples (map, mapset)
  505. """
  506. return _concat([[(map, mapset) for map in maps]
  507. for mapset, maps in list_grouped(type).iteritems()])
  508. def list_strings(type):
  509. """!List of elements as strings.
  510. Returns the output from running g.list, as a list of qualified
  511. names. Example:
  512. @code
  513. >>> grass.list_strings('rast')
  514. ['aspect@PERMANENT', 'erosion1@PERMANENT', 'quads@PERMANENT', 'soils@PERMANENT', ...
  515. @endcode
  516. @param type element type
  517. @return list of strings ('map@@mapset')
  518. """
  519. return ["%s@%s" % pair for pair in list_pairs(type)]
  520. # interface to g.mlist
  521. def mlist(type, pattern = None, mapset = None):
  522. """!List of elements
  523. @param type element type (rast, vect, rast3d, region, ...)
  524. @param pattern pattern string
  525. @param mapset mapset name (if not given use search path)
  526. @return list of elements
  527. """
  528. result = list()
  529. for line in read_command("g.mlist",
  530. type = type,
  531. pattern = pattern,
  532. mapset = mapset).splitlines():
  533. result.append(line.strip())
  534. return result
  535. def mlist_grouped(type, pattern = None):
  536. """!List of elements grouped by mapsets.
  537. Returns the output from running g.mlist, as a dictionary where the
  538. keys are mapset names and the values are lists of maps in that
  539. mapset. Example:
  540. @code
  541. >>> grass.mlist_grouped('rast', pattern='r*')['PERMANENT']
  542. ['railroads', 'roads', 'rstrct.areas', 'rushmore']
  543. @endcode
  544. @param type element type (rast, vect, rast3d, region, ...)
  545. @param pattern pattern string
  546. @return directory of mapsets/elements
  547. """
  548. result = dict()
  549. mapset_element = None
  550. for line in read_command("g.mlist", flags = "m",
  551. type = type, pattern = pattern).splitlines():
  552. try:
  553. map, mapset_element = line.split('@')
  554. except ValueError:
  555. warning(_("Invalid element '%s'") % line)
  556. continue
  557. if result.has_key(mapset_element):
  558. result[mapset_element].append(map)
  559. else:
  560. result[mapset_element] = [map, ]
  561. return result
  562. # color parsing
  563. named_colors = {
  564. "white": (1.00, 1.00, 1.00),
  565. "black": (0.00, 0.00, 0.00),
  566. "red": (1.00, 0.00, 0.00),
  567. "green": (0.00, 1.00, 0.00),
  568. "blue": (0.00, 0.00, 1.00),
  569. "yellow": (1.00, 1.00, 0.00),
  570. "magenta": (1.00, 0.00, 1.00),
  571. "cyan": (0.00, 1.00, 1.00),
  572. "aqua": (0.00, 0.75, 0.75),
  573. "grey": (0.75, 0.75, 0.75),
  574. "gray": (0.75, 0.75, 0.75),
  575. "orange": (1.00, 0.50, 0.00),
  576. "brown": (0.75, 0.50, 0.25),
  577. "purple": (0.50, 0.00, 1.00),
  578. "violet": (0.50, 0.00, 1.00),
  579. "indigo": (0.00, 0.50, 1.00)}
  580. def parse_color(val, dflt = None):
  581. """!Parses the string "val" as a GRASS colour, which can be either one of
  582. the named colours or an R:G:B tuple e.g. 255:255:255. Returns an
  583. (r,g,b) triple whose components are floating point values between 0
  584. and 1. Example:
  585. \code
  586. >>> grass.parse_color("red")
  587. (1.0, 0.0, 0.0)
  588. >>> grass.parse_color("255:0:0")
  589. (1.0, 0.0, 0.0)
  590. \endcode
  591. @param val color value
  592. @param dflt default color value
  593. @return tuple RGB
  594. """
  595. if val in named_colors:
  596. return named_colors[val]
  597. vals = val.split(':')
  598. if len(vals) == 3:
  599. return tuple(float(v) / 255 for v in vals)
  600. return dflt
  601. # check GRASS_OVERWRITE
  602. def overwrite():
  603. """!Return True if existing files may be overwritten"""
  604. owstr = 'GRASS_OVERWRITE'
  605. return owstr in os.environ and os.environ[owstr] != '0'
  606. # check GRASS_VERBOSE
  607. def verbosity():
  608. """!Return the verbosity level selected by GRASS_VERBOSE"""
  609. vbstr = os.getenv('GRASS_VERBOSE')
  610. if vbstr:
  611. return int(vbstr)
  612. else:
  613. return 2
  614. ## various utilities, not specific to GRASS
  615. # basename inc. extension stripping
  616. def basename(path, ext = None):
  617. """!Remove leading directory components and an optional extension
  618. from the specified path
  619. @param path path
  620. @param ext extension
  621. """
  622. name = os.path.basename(path)
  623. if not ext:
  624. return name
  625. fs = name.rsplit('.', 1)
  626. if len(fs) > 1 and fs[1].lower() == ext:
  627. name = fs[0]
  628. return name
  629. # find a program (replacement for "which")
  630. def find_program(pgm, args = []):
  631. """!Attempt to run a program, with optional arguments.
  632. @param pgm program name
  633. @param args list of arguments
  634. @return False if the attempt failed due to a missing executable
  635. @return True otherwise
  636. """
  637. nuldev = file(os.devnull, 'w+')
  638. try:
  639. ret = call([pgm] + args, stdin = nuldev, stdout = nuldev, stderr = nuldev)
  640. if ret == 0:
  641. found = True
  642. else:
  643. found = False
  644. except:
  645. found = False
  646. nuldev.close()
  647. return found
  648. # try to remove a file, without complaints
  649. def try_remove(path):
  650. """!Attempt to remove a file; no exception is generated if the
  651. attempt fails.
  652. @param path path to file to remove
  653. """
  654. try:
  655. os.remove(path)
  656. except:
  657. pass
  658. # try to remove a directory, without complaints
  659. def try_rmdir(path):
  660. """!Attempt to remove a directory; no exception is generated if the
  661. attempt fails.
  662. @param path path to directory to remove
  663. """
  664. try:
  665. os.rmdir(path)
  666. except:
  667. shutil.rmtree(path, ignore_errors = True)
  668. def float_or_dms(s):
  669. """!Convert DMS to float.
  670. @param s DMS value
  671. @return float value
  672. """
  673. return sum(float(x) / 60 ** n for (n, x) in enumerate(s.split(':')))
  674. def command_info(cmd):
  675. """!Returns 'help' information for any command as dictionary with entries
  676. for description, keywords, usage, flags, and parameters"""
  677. cmdinfo = {}
  678. s = start_command(cmd, 'help', stdout = subprocess.PIPE, stderr = subprocess.PIPE)
  679. out, err = s.communicate()
  680. sections = err.split('\n\n')
  681. #Description
  682. first, desc = sections[0].split(':\n', 1)
  683. desclines = desc.splitlines()
  684. for line in desclines:
  685. line = line.strip()+' '
  686. # Keywords
  687. first, keywords = sections[1].split(':\n', 1)
  688. keylines = keywords.splitlines()
  689. list = []
  690. list = keywords.strip().split(',')
  691. cmdinfo['keywords'] = list
  692. cmdinfo['description'] = ''.join(desclines).strip()
  693. # Usage
  694. first, usage = sections[2].split(':\n', 1)
  695. usagelines = usage.splitlines()
  696. list = []
  697. for line in usagelines:
  698. line = line.strip()
  699. if line == '': continue
  700. line = line+' '
  701. list.append(line)
  702. cmdinfo['usage'] = ''.join(list).strip()
  703. # Flags
  704. first, flags = sections[3].split(':\n', 1)
  705. flaglines = flags.splitlines()
  706. dict = {}
  707. for line in flaglines:
  708. line = line.strip()
  709. if line == '': continue
  710. item = line.split(' ',1)[0].strip()
  711. val = line.split(' ',1)[1].strip()
  712. dict[item] = val
  713. cmdinfo['flags'] = dict
  714. # Parameters
  715. first, params = err.rsplit(':\n', 1)
  716. paramlines = params.splitlines()
  717. dict = {}
  718. for line in paramlines:
  719. line = line.strip()
  720. if line == '': continue
  721. item = line.split(' ',1)[0].strip()
  722. val = line.split(' ',1)[1].strip()
  723. dict[item] = val
  724. cmdinfo['parameters'] = dict
  725. return cmdinfo
  726. # interface to g.mapsets
  727. def mapsets(accessible = True):
  728. """!List accessible mapsets (mapsets in search path)
  729. @param accessible False to list all mapsets in the location
  730. @return list of mapsets
  731. """
  732. if accessible:
  733. flags = 'p'
  734. else:
  735. flags = 'l'
  736. mapsets = read_command('g.mapsets',
  737. flags = flags,
  738. fs = 'newline',
  739. quiet = True)
  740. if not mapsets:
  741. fatal(_("Unable to list mapsets"))
  742. return mapsets.splitlines()
  743. # interface to `g.proj -c`
  744. def create_location(dbase, location,
  745. epsg = None, proj4 = None, filename = None, wkt = None,
  746. datum = None, desc = None):
  747. """!Create new location
  748. Raise ScriptException on error.
  749. @param dbase path to GRASS database
  750. @param location location name to create
  751. @param epgs if given create new location based on EPSG code
  752. @param proj4 if given create new location based on Proj4 definition
  753. @param filename if given create new location based on georeferenced file
  754. @param wkt if given create new location based on WKT definition (path to PRJ file)
  755. @param datum datum transformation parameters (used for epsg and proj4)
  756. @param desc description of the location (creates MYNAME file)
  757. """
  758. gisdbase = None
  759. if epsg or proj4 or filename or wkt:
  760. gisdbase = gisenv()['GISDBASE']
  761. run_command('g.gisenv',
  762. set = 'GISDBASE=%s' % dbase)
  763. if not os.path.exists(dbase):
  764. os.mkdir(dbase)
  765. kwargs = dict()
  766. if datum:
  767. kwargs['datum'] = datum
  768. if epsg:
  769. ps = pipe_command('g.proj',
  770. quiet = True,
  771. flags = 'c',
  772. epsg = epsg,
  773. location = location,
  774. stderr = PIPE,
  775. **kwargs)
  776. elif proj4:
  777. ps = pipe_command('g.proj',
  778. quiet = True,
  779. flags = 'c',
  780. proj4 = proj4,
  781. location = location,
  782. stderr = PIPE,
  783. **kwargs)
  784. elif filename:
  785. ps = pipe_command('g.proj',
  786. quiet = True,
  787. flags = 'c',
  788. georef = filename,
  789. location = location,
  790. stderr = PIPE)
  791. elif wkt:
  792. ps = pipe_command('g.proj',
  793. quiet = True,
  794. flags = 'c',
  795. wkt = wktfile,
  796. location = location,
  797. stderr = PIPE)
  798. else:
  799. _create_location_xy(dbase, location)
  800. if epsg or proj4 or filename or wkt:
  801. error = ps.communicate()[1]
  802. run_command('g.gisenv',
  803. set = 'GISDBASE=%s' % gisdbase)
  804. if ps.returncode != 0 and error:
  805. raise ScriptException(repr(error))
  806. try:
  807. fd = open(os.path.join(dbase, location,
  808. 'PERMANENT', 'MYNAME'), 'w')
  809. if desc:
  810. fd.write(desc + os.linesep)
  811. else:
  812. fd.write(os.linesep)
  813. fd.close()
  814. except OSError, e:
  815. raise ScriptException(repr(e))
  816. def _create_location_xy(database, location):
  817. """!Create unprojected location
  818. Raise ScriptException on error.
  819. @param database GRASS database where to create new location
  820. @param location location name
  821. """
  822. cur_dir = os.getcwd()
  823. try:
  824. os.chdir(database)
  825. os.mkdir(location)
  826. os.mkdir(os.path.join(location, 'PERMANENT'))
  827. # create DEFAULT_WIND and WIND files
  828. regioninfo = ['proj: 0',
  829. 'zone: 0',
  830. 'north: 1',
  831. 'south: 0',
  832. 'east: 1',
  833. 'west: 0',
  834. 'cols: 1',
  835. 'rows: 1',
  836. 'e-w resol: 1',
  837. 'n-s resol: 1',
  838. 'top: 1',
  839. 'bottom: 0',
  840. 'cols3: 1',
  841. 'rows3: 1',
  842. 'depths: 1',
  843. 'e-w resol3: 1',
  844. 'n-s resol3: 1',
  845. 't-b resol: 1']
  846. defwind = open(os.path.join(location,
  847. "PERMANENT", "DEFAULT_WIND"), 'w')
  848. for param in regioninfo:
  849. defwind.write(param + '%s' % os.linesep)
  850. defwind.close()
  851. shutil.copy(os.path.join(location, "PERMANENT", "DEFAULT_WIND"),
  852. os.path.join(location, "PERMANENT", "WIND"))
  853. os.chdir(cur_dir)
  854. except OSError, e:
  855. raise ScriptException(repr(e))
  856. # interface to g.version
  857. def version():
  858. """!Get GRASS version as dictionary
  859. @code
  860. version()
  861. {'date': '2011', 'libgis_revision': '45093 ', 'version': '7.0.svn',
  862. 'libgis_date': '2011-01-20 13:10:50 +0100 (Thu, 20 Jan 2011) ', 'revision': '45136M'}
  863. @endcode
  864. """
  865. return parse_command('g.version',
  866. flags = 'rg')
  867. # get debug_level
  868. if find_program('g.gisenv', ['--help']):
  869. debug_level = int(gisenv().get('DEBUG', 0))