core.py 32 KB

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