core.py 29 KB

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