core.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  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'))
  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 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. 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. 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 environmental 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(create = True):
  369. """!Returns the name of a temporary file, created with
  370. g.tempfile.
  371. @param create True to create a file
  372. @return path to a tmp file
  373. """
  374. flags = ''
  375. if not create:
  376. flags += 'd'
  377. return read_command("g.tempfile", flags = flags, pid = os.getpid()).strip()
  378. def tempdir():
  379. """!Returns the name of a temporary dir, created with g.tempfile."""
  380. tmp = tempfile(create = False)
  381. os.mkdir(tmp)
  382. return tmp
  383. class KeyValue(dict):
  384. """A general-purpose key-value store.
  385. KeyValue is a subclass of dict, but also allows entries to be read and
  386. written using attribute syntax. Example:
  387. \code
  388. >>> region = grass.region()
  389. >>> region['rows']
  390. 477
  391. >>> region.rows
  392. 477
  393. \endcode
  394. """
  395. def __getattr__(self, key):
  396. return self[key]
  397. def __setattr__(self, key, value):
  398. self[key] = value
  399. # key-value parsers
  400. def parse_key_val(s, sep = '=', dflt = None, val_type = None, vsep = None):
  401. """!Parse a string into a dictionary, where entries are separated
  402. by newlines and the key and value are separated by `sep' (default: `=')
  403. @param s string to be parsed
  404. @param sep key/value separator
  405. @param dflt default value to be used
  406. @param val_type value type (None for no cast)
  407. @param vsep vertical separator (default os.linesep)
  408. @return parsed input (dictionary of keys/values)
  409. """
  410. result = KeyValue()
  411. if not s:
  412. return result
  413. if vsep:
  414. lines = s.split(vsep)
  415. try:
  416. lines.remove('\n')
  417. except ValueError:
  418. pass
  419. else:
  420. lines = s.splitlines()
  421. for line in lines:
  422. kv = line.split(sep, 1)
  423. k = kv[0].strip()
  424. if len(kv) > 1:
  425. v = kv[1]
  426. else:
  427. v = dflt
  428. if val_type:
  429. result[k] = val_type(v)
  430. else:
  431. result[k] = v
  432. return result
  433. # interface to g.gisenv
  434. def gisenv():
  435. """!Returns the output from running g.gisenv (with no arguments), as a
  436. dictionary. Example:
  437. \code
  438. >>> env = grass.gisenv()
  439. >>> print env['GISDBASE']
  440. /opt/grass-data
  441. \endcode
  442. @return list of GRASS variables
  443. """
  444. s = read_command("g.gisenv", flags='n')
  445. return parse_key_val(s)
  446. # interface to g.region
  447. def locn_is_latlong():
  448. """!Tests if location is lat/long. Value is obtained
  449. by checking the "g.region -p" projection code.
  450. @return True for a lat/long region, False otherwise
  451. """
  452. s = read_command("g.region", flags='p')
  453. kv = parse_key_val(s, ':')
  454. if kv['projection'].split(' ')[1] == '3':
  455. return True
  456. else:
  457. return False
  458. def region(region3d = False):
  459. """!Returns the output from running "g.region -g", as a
  460. dictionary. Example:
  461. \param region3d True to get 3D region
  462. \code
  463. >>> region = grass.region()
  464. >>> [region[key] for key in "nsew"]
  465. [228500.0, 215000.0, 645000.0, 630000.0]
  466. >>> (region['nsres'], region['ewres'])
  467. (10.0, 10.0)
  468. \endcode
  469. @return dictionary of region values
  470. """
  471. flgs = 'g'
  472. if region3d:
  473. flgs += '3'
  474. s = read_command("g.region", flags = flgs)
  475. reg = parse_key_val(s, val_type = float)
  476. for k in ['rows', 'cols', 'cells',
  477. 'rows3', 'cols3', 'cells3', 'depths']:
  478. if k not in reg:
  479. continue
  480. reg[k] = int(reg[k])
  481. return reg
  482. def region_env(region3d = False,
  483. **kwargs):
  484. """!Returns region settings as a string which can used as
  485. GRASS_REGION environmental variable.
  486. If no 'kwargs' are given then the current region is used. Note
  487. that this function doesn't modify the current region!
  488. See also use_temp_region() for alternative method how to define
  489. temporary region used for raster-based computation.
  490. \param region3d True to get 3D region
  491. \param kwargs g.region's parameters like 'rast', 'vect' or 'region'
  492. \code
  493. os.environ['GRASS_REGION'] = grass.region_env(region = 'detail')
  494. grass.mapcalc('map = 1', overwrite = True)
  495. os.environ.pop('GRASS_REGION')
  496. \endcode
  497. @return string with region values
  498. @return empty string on error
  499. """
  500. # read proj/zone from WIND file
  501. env = gisenv()
  502. windfile = os.path.join (env['GISDBASE'], env['LOCATION_NAME'],
  503. env['MAPSET'], "WIND")
  504. fd = open(windfile, "r")
  505. grass_region = ''
  506. for line in fd.readlines():
  507. key, value = map(lambda x: x.strip(), line.split(":", 1))
  508. if kwargs and key not in ('proj', 'zone'):
  509. continue
  510. if not kwargs and not region3d and \
  511. key in ('top', 'bottom', 'cols3', 'rows3',
  512. 'depths', 'e-w resol3', 'n-s resol3', 't-b resol'):
  513. continue
  514. grass_region += '%s: %s;' % (key, value)
  515. if not kwargs: # return current region
  516. return grass_region
  517. # read other values from `g.region -g`
  518. flgs = 'ug'
  519. if region3d:
  520. flgs += '3'
  521. s = read_command('g.region', flags = flgs, **kwargs)
  522. if not s:
  523. return ''
  524. reg = parse_key_val(s)
  525. kwdata = [('north', 'n'),
  526. ('south', 's'),
  527. ('east', 'e'),
  528. ('west', 'w'),
  529. ('cols', 'cols'),
  530. ('rows', 'rows'),
  531. ('e-w resol', 'ewres'),
  532. ('n-s resol', 'nsres')]
  533. if region3d:
  534. kwdata += [('top', 't'),
  535. ('bottom', 'b'),
  536. ('cols3', 'cols3'),
  537. ('rows3', 'rows3'),
  538. ('depths', 'depths'),
  539. ('e-w resol3', 'ewres3'),
  540. ('n-s resol3', 'nsres3'),
  541. ('t-b resol', 'tbres')]
  542. for wkey, rkey in kwdata:
  543. grass_region += '%s: %s;' % (wkey, reg[rkey])
  544. return grass_region
  545. def use_temp_region():
  546. """!Copies the current region to a temporary region with "g.region save=",
  547. then sets WIND_OVERRIDE to refer to that region. Installs an atexit
  548. handler to delete the temporary region upon termination.
  549. """
  550. name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
  551. run_command("g.region", save = name, overwrite = True)
  552. os.environ['WIND_OVERRIDE'] = name
  553. atexit.register(del_temp_region)
  554. def del_temp_region():
  555. """!Unsets WIND_OVERRIDE and removes any region named by it."""
  556. try:
  557. name = os.environ.pop('WIND_OVERRIDE')
  558. run_command("g.remove", quiet = True, region = name)
  559. except:
  560. pass
  561. # interface to g.findfile
  562. def find_file(name, element = 'cell', mapset = None):
  563. """!Returns the output from running g.findfile as a
  564. dictionary. Example:
  565. \code
  566. >>> result = grass.find_file('fields', element = 'vector')
  567. >>> print result['fullname']
  568. fields@PERMANENT
  569. >>> print result['file']
  570. /opt/grass-data/spearfish60/PERMANENT/vector/fields
  571. \endcode
  572. @param name file name
  573. @param element element type (default 'cell')
  574. @param mapset mapset name (default all mapsets in search path)
  575. @return parsed output of g.findfile
  576. """
  577. if element == 'raster' or element == 'rast':
  578. verbose(_('Element type should be "cell" and not "%s"') % element)
  579. element = 'cell'
  580. s = read_command("g.findfile", flags='n', element = element, file = name, mapset = mapset)
  581. return parse_key_val(s)
  582. # interface to g.list
  583. def list_grouped(type, check_search_path = True):
  584. """!List elements grouped by mapsets.
  585. Returns the output from running g.list, 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.list_grouped('rast')['PERMANENT']
  590. ['aspect', 'erosion1', 'quads', 'soils', 'strm.dist', ...
  591. @endcode
  592. @param type element type (rast, vect, rast3d, region, ...)
  593. @param check_search_path True to add mapsets for the search path with no found elements
  594. @return directory of mapsets/elements
  595. """
  596. if type == 'raster' or type == 'cell':
  597. verbose(_('Element type should be "rast" and not "%s"') % element)
  598. type = 'rast'
  599. dashes_re = re.compile("^----+$")
  600. mapset_re = re.compile("<(.*)>")
  601. result = {}
  602. if check_search_path:
  603. for mapset in mapsets(search_path = True):
  604. result[mapset] = []
  605. mapset = None
  606. for line in read_command("g.list", type = type).splitlines():
  607. if line == "":
  608. continue
  609. if dashes_re.match(line):
  610. continue
  611. m = mapset_re.search(line)
  612. if m:
  613. mapset = m.group(1)
  614. if mapset not in result.keys():
  615. result[mapset] = []
  616. continue
  617. if mapset:
  618. result[mapset].extend(line.split())
  619. return result
  620. def _concat(xs):
  621. result = []
  622. for x in xs:
  623. result.extend(x)
  624. return result
  625. def list_pairs(type):
  626. """!List of elements as tuples.
  627. Returns the output from running g.list, as a list of (map, mapset)
  628. pairs. Example:
  629. @code
  630. >>> grass.list_pairs('rast')
  631. [('aspect', 'PERMANENT'), ('erosion1', 'PERMANENT'), ('quads', 'PERMANENT'), ...
  632. @endcode
  633. @param type element type (rast, vect, rast3d, region, ...)
  634. @return list of tuples (map, mapset)
  635. """
  636. return _concat([[(map, mapset) for map in maps]
  637. for mapset, maps in list_grouped(type).iteritems()])
  638. def list_strings(type):
  639. """!List of elements as strings.
  640. Returns the output from running g.list, as a list of qualified
  641. names. Example:
  642. @code
  643. >>> grass.list_strings('rast')
  644. ['aspect@PERMANENT', 'erosion1@PERMANENT', 'quads@PERMANENT', 'soils@PERMANENT', ...
  645. @endcode
  646. @param type element type
  647. @return list of strings ('map@@mapset')
  648. """
  649. return ["%s@%s" % pair for pair in list_pairs(type)]
  650. # interface to g.mlist
  651. def mlist_strings(type, pattern = None, mapset = None, flag = ''):
  652. """!List of elements as strings.
  653. Returns the output from running g.mlist, as a list of qualified
  654. names.
  655. @param type element type (rast, vect, rast3d, region, ...)
  656. @param pattern pattern string
  657. @param mapset mapset name (if not given use search path)
  658. @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or '' (glob pattern)
  659. @return list of elements
  660. """
  661. if type == 'raster' or type == 'cell':
  662. verbose(_('Element type should be "rast" and not "%s"') % element)
  663. type = 'rast'
  664. result = list()
  665. for line in read_command("g.mlist",
  666. quiet = True,
  667. flags = 'm' + flag,
  668. type = type,
  669. pattern = pattern,
  670. mapset = mapset).splitlines():
  671. result.append(line.strip())
  672. return result
  673. def mlist_pairs(type, pattern = None, mapset = None, flag = ''):
  674. """!List of elements as pairs
  675. Returns the output from running g.mlist, as a list of
  676. (name, mapset) pairs
  677. @param type element type (rast, vect, rast3d, region, ...)
  678. @param pattern pattern string
  679. @param mapset mapset name (if not given use search path)
  680. @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or '' (glob pattern)
  681. @return list of elements
  682. """
  683. return [tuple(map.split('@', 1)) for map in mlist_strings(type, pattern, mapset, flag)]
  684. def mlist_grouped(type, pattern = None, check_search_path = True, flag = ''):
  685. """!List of elements grouped by mapsets.
  686. Returns the output from running g.mlist, as a dictionary where the
  687. keys are mapset names and the values are lists of maps in that
  688. mapset. Example:
  689. @code
  690. >>> grass.mlist_grouped('rast', pattern='r*')['PERMANENT']
  691. ['railroads', 'roads', 'rstrct.areas', 'rushmore']
  692. @endcode
  693. @param type element type (rast, vect, rast3d, region, ...)
  694. @param pattern pattern string
  695. @param check_search_path True to add mapsets for the search path with no found elements
  696. @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or '' (glob pattern)
  697. @return directory of mapsets/elements
  698. """
  699. if type == 'raster' or type == 'cell':
  700. verbose(_('Element type should be "rast" and not "%s"') % element)
  701. type = 'rast'
  702. result = {}
  703. if check_search_path:
  704. for mapset in mapsets(search_path = True):
  705. result[mapset] = []
  706. mapset = None
  707. for line in read_command("g.mlist", quiet = True, flags = "m" + flag,
  708. type = type, pattern = pattern).splitlines():
  709. try:
  710. name, mapset = line.split('@')
  711. except ValueError:
  712. warning(_("Invalid element '%s'") % line)
  713. continue
  714. if mapset in result:
  715. result[mapset].append(name)
  716. else:
  717. result[mapset] = [name, ]
  718. return result
  719. # color parsing
  720. named_colors = {
  721. "white": (1.00, 1.00, 1.00),
  722. "black": (0.00, 0.00, 0.00),
  723. "red": (1.00, 0.00, 0.00),
  724. "green": (0.00, 1.00, 0.00),
  725. "blue": (0.00, 0.00, 1.00),
  726. "yellow": (1.00, 1.00, 0.00),
  727. "magenta": (1.00, 0.00, 1.00),
  728. "cyan": (0.00, 1.00, 1.00),
  729. "aqua": (0.00, 0.75, 0.75),
  730. "grey": (0.75, 0.75, 0.75),
  731. "gray": (0.75, 0.75, 0.75),
  732. "orange": (1.00, 0.50, 0.00),
  733. "brown": (0.75, 0.50, 0.25),
  734. "purple": (0.50, 0.00, 1.00),
  735. "violet": (0.50, 0.00, 1.00),
  736. "indigo": (0.00, 0.50, 1.00)}
  737. def parse_color(val, dflt = None):
  738. """!Parses the string "val" as a GRASS colour, which can be either one of
  739. the named colours or an R:G:B tuple e.g. 255:255:255. Returns an
  740. (r,g,b) triple whose components are floating point values between 0
  741. and 1. Example:
  742. \code
  743. >>> grass.parse_color("red")
  744. (1.0, 0.0, 0.0)
  745. >>> grass.parse_color("255:0:0")
  746. (1.0, 0.0, 0.0)
  747. \endcode
  748. @param val color value
  749. @param dflt default color value
  750. @return tuple RGB
  751. """
  752. if val in named_colors:
  753. return named_colors[val]
  754. vals = val.split(':')
  755. if len(vals) == 3:
  756. return tuple(float(v) / 255 for v in vals)
  757. return dflt
  758. # check GRASS_OVERWRITE
  759. def overwrite():
  760. """!Return True if existing files may be overwritten"""
  761. owstr = 'GRASS_OVERWRITE'
  762. return owstr in os.environ and os.environ[owstr] != '0'
  763. # check GRASS_VERBOSE
  764. def verbosity():
  765. """!Return the verbosity level selected by GRASS_VERBOSE"""
  766. vbstr = os.getenv('GRASS_VERBOSE')
  767. if vbstr:
  768. return int(vbstr)
  769. else:
  770. return 2
  771. ## various utilities, not specific to GRASS
  772. # basename inc. extension stripping
  773. def basename(path, ext = None):
  774. """!Remove leading directory components and an optional extension
  775. from the specified path
  776. @param path path
  777. @param ext extension
  778. """
  779. name = os.path.basename(path)
  780. if not ext:
  781. return name
  782. fs = name.rsplit('.', 1)
  783. if len(fs) > 1 and fs[1].lower() == ext:
  784. name = fs[0]
  785. return name
  786. # find a program (replacement for "which")
  787. def find_program(pgm, args = []):
  788. """!Attempt to run a program, with optional arguments.
  789. @param pgm program name
  790. @param args list of arguments
  791. @return False if the attempt failed due to a missing executable
  792. @return True otherwise
  793. """
  794. nuldev = file(os.devnull, 'w+')
  795. try:
  796. ret = call([pgm] + args, stdin = nuldev, stdout = nuldev, stderr = nuldev)
  797. if ret == 0:
  798. found = True
  799. else:
  800. found = False
  801. except:
  802. found = False
  803. nuldev.close()
  804. return found
  805. # try to remove a file, without complaints
  806. def try_remove(path):
  807. """!Attempt to remove a file; no exception is generated if the
  808. attempt fails.
  809. @param path path to file to remove
  810. """
  811. try:
  812. os.remove(path)
  813. except:
  814. pass
  815. # try to remove a directory, without complaints
  816. def try_rmdir(path):
  817. """!Attempt to remove a directory; no exception is generated if the
  818. attempt fails.
  819. @param path path to directory to remove
  820. """
  821. try:
  822. os.rmdir(path)
  823. except:
  824. shutil.rmtree(path, ignore_errors = True)
  825. def float_or_dms(s):
  826. """!Convert DMS to float.
  827. @param s DMS value
  828. @return float value
  829. """
  830. return sum(float(x) / 60 ** n for (n, x) in enumerate(s.split(':')))
  831. # interface to g.mapsets
  832. def mapsets(search_path = False):
  833. """!List available mapsets
  834. @param searchPatch True to list mapsets only in search path
  835. @return list of mapsets
  836. """
  837. if search_path:
  838. flags = 'p'
  839. else:
  840. flags = 'l'
  841. mapsets = read_command('g.mapsets',
  842. flags = flags,
  843. fs = 'newline',
  844. quiet = True)
  845. if not mapsets:
  846. fatal(_("Unable to list mapsets"))
  847. return mapsets.splitlines()
  848. # interface to `g.proj -c`
  849. def create_location(dbase, location,
  850. epsg = None, proj4 = None, filename = None, wkt = None,
  851. datum = None, desc = None):
  852. """!Create new location
  853. Raise ScriptError on error.
  854. @param dbase path to GRASS database
  855. @param location location name to create
  856. @param epgs if given create new location based on EPSG code
  857. @param proj4 if given create new location based on Proj4 definition
  858. @param filename if given create new location based on georeferenced file
  859. @param wkt if given create new location based on WKT definition (path to PRJ file)
  860. @param datum datum transformation parameters (used for epsg and proj4)
  861. @param desc description of the location (creates MYNAME file)
  862. """
  863. gisdbase = None
  864. if epsg or proj4 or filename or wkt:
  865. gisdbase = gisenv()['GISDBASE']
  866. run_command('g.gisenv',
  867. set = 'GISDBASE=%s' % dbase)
  868. if not os.path.exists(dbase):
  869. os.mkdir(dbase)
  870. kwargs = dict()
  871. if datum:
  872. kwargs['datum'] = datum
  873. if epsg:
  874. ps = pipe_command('g.proj',
  875. quiet = True,
  876. epsg = epsg,
  877. location = location,
  878. stderr = PIPE,
  879. **kwargs)
  880. elif proj4:
  881. ps = pipe_command('g.proj',
  882. quiet = True,
  883. proj4 = proj4,
  884. location = location,
  885. stderr = PIPE,
  886. **kwargs)
  887. elif filename:
  888. ps = pipe_command('g.proj',
  889. quiet = True,
  890. georef = filename,
  891. location = location,
  892. stderr = PIPE)
  893. elif wkt:
  894. ps = pipe_command('g.proj',
  895. quiet = True,
  896. wkt = wkt,
  897. location = location,
  898. stderr = PIPE)
  899. else:
  900. _create_location_xy(dbase, location)
  901. if epsg or proj4 or filename or wkt:
  902. error = ps.communicate()[1]
  903. run_command('g.gisenv',
  904. set = 'GISDBASE=%s' % gisdbase)
  905. if ps.returncode != 0 and error:
  906. raise ScriptError(repr(error))
  907. try:
  908. fd = codecs.open(os.path.join(dbase, location,
  909. 'PERMANENT', 'MYNAME'),
  910. encoding = 'utf-8', mode = 'w')
  911. if desc:
  912. fd.write(desc + os.linesep)
  913. else:
  914. fd.write(os.linesep)
  915. fd.close()
  916. except OSError, e:
  917. raise ScriptError(repr(e))
  918. def _create_location_xy(database, location):
  919. """!Create unprojected location
  920. Raise ScriptError on error.
  921. @param database GRASS database where to create new location
  922. @param location location name
  923. """
  924. cur_dir = os.getcwd()
  925. try:
  926. os.chdir(database)
  927. os.mkdir(location)
  928. os.mkdir(os.path.join(location, 'PERMANENT'))
  929. # create DEFAULT_WIND and WIND files
  930. regioninfo = ['proj: 0',
  931. 'zone: 0',
  932. 'north: 1',
  933. 'south: 0',
  934. 'east: 1',
  935. 'west: 0',
  936. 'cols: 1',
  937. 'rows: 1',
  938. 'e-w resol: 1',
  939. 'n-s resol: 1',
  940. 'top: 1',
  941. 'bottom: 0',
  942. 'cols3: 1',
  943. 'rows3: 1',
  944. 'depths: 1',
  945. 'e-w resol3: 1',
  946. 'n-s resol3: 1',
  947. 't-b resol: 1']
  948. defwind = open(os.path.join(location,
  949. "PERMANENT", "DEFAULT_WIND"), 'w')
  950. for param in regioninfo:
  951. defwind.write(param + '%s' % os.linesep)
  952. defwind.close()
  953. shutil.copy(os.path.join(location, "PERMANENT", "DEFAULT_WIND"),
  954. os.path.join(location, "PERMANENT", "WIND"))
  955. os.chdir(cur_dir)
  956. except OSError, e:
  957. raise ScriptError(repr(e))
  958. # interface to g.version
  959. def version():
  960. """!Get GRASS version as dictionary
  961. @code
  962. print version()
  963. {'date': '2011', 'libgis_date': '2011-08-13 01:14:30 +0200 (Sat, 13 Aug 2011)',
  964. 'version': '7.0.svn', 'libgis_revision': '47604', 'revision': '47963'}
  965. @endcode
  966. """
  967. data = parse_command('g.version',
  968. flags = 'rg')
  969. for k, v in data.iteritems():
  970. data[k.strip()] = v.replace('"', '').strip()
  971. return data
  972. # get debug_level
  973. if find_program('g.gisenv', ['--help']):
  974. debug_level = int(gisenv().get('DEBUG', 0))