core.py 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  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 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. 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. if sys.platform == 'win32' and os.path.splitext(prog)[1] == '.py':
  138. os.chdir(os.path.join(os.getenv('GISBASE'), 'scripts'))
  139. args.insert(0, sys.executable)
  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. ps = start_command(*args, **kwargs)
  154. return ps.wait()
  155. def pipe_command(*args, **kwargs):
  156. """!Passes all arguments to start_command(), but also adds
  157. "stdout = PIPE". Returns the Popen object.
  158. \code
  159. >>> p = grass.pipe_command("g.gisenv")
  160. >>> print p
  161. <subprocess.Popen object at 0xb7c12f6c>
  162. >>> print p.communicate()[0]
  163. GISDBASE='/opt/grass-data';
  164. LOCATION_NAME='spearfish60';
  165. MAPSET='glynn';
  166. GRASS_DB_ENCODING='ascii';
  167. GUI='text';
  168. MONITOR='x0';
  169. \endcode
  170. @param args list of unnamed arguments (see start_command() for details)
  171. @param kwargs list of named arguments (see start_command() for details)
  172. @return Popen object
  173. """
  174. kwargs['stdout'] = PIPE
  175. return start_command(*args, **kwargs)
  176. def feed_command(*args, **kwargs):
  177. """!Passes all arguments to start_command(), but also adds
  178. "stdin = PIPE". Returns the Popen object.
  179. @param args list of unnamed arguments (see start_command() for details)
  180. @param kwargs list of named arguments (see start_command() for details)
  181. @return Popen object
  182. """
  183. kwargs['stdin'] = PIPE
  184. return start_command(*args, **kwargs)
  185. def read_command(*args, **kwargs):
  186. """!Passes all arguments to pipe_command, then waits for the process to
  187. complete, returning its stdout (i.e. similar to shell `backticks`).
  188. @param args list of unnamed arguments (see start_command() for details)
  189. @param kwargs list of named arguments (see start_command() for details)
  190. @return stdout
  191. """
  192. ps = pipe_command(*args, **kwargs)
  193. return ps.communicate()[0]
  194. def parse_command(*args, **kwargs):
  195. """!Passes all arguments to read_command, then parses the output
  196. by parse_key_val().
  197. Parsing function can be optionally given by <em>parse</em> parameter
  198. including its arguments, e.g.
  199. @code
  200. parse_command(..., parse = (grass.parse_key_val, { 'sep' : ':' }))
  201. @endcode
  202. or you can simply define <em>delimiter</em>
  203. @code
  204. parse_command(..., delimiter = ':')
  205. @endcode
  206. @param args list of unnamed arguments (see start_command() for details)
  207. @param kwargs list of named arguments (see start_command() for details)
  208. @return parsed module output
  209. """
  210. parse = None
  211. parse_args = {}
  212. if 'parse' in kwargs:
  213. if type(kwargs['parse']) is types.TupleType:
  214. parse = kwargs['parse'][0]
  215. parse_args = kwargs['parse'][1]
  216. del kwargs['parse']
  217. if 'delimiter' in kwargs:
  218. parse_args = { 'sep' : kwargs['delimiter'] }
  219. del kwargs['delimiter']
  220. if not parse:
  221. parse = parse_key_val # use default fn
  222. res = read_command(*args, **kwargs)
  223. return parse(res, **parse_args)
  224. def write_command(*args, **kwargs):
  225. """!Passes all arguments to feed_command, with the string specified
  226. by the 'stdin' argument fed to the process' stdin.
  227. @param args list of unnamed arguments (see start_command() for details)
  228. @param kwargs list of named arguments (see start_command() for details)
  229. @return return code
  230. """
  231. stdin = kwargs['stdin']
  232. p = feed_command(*args, **kwargs)
  233. p.stdin.write(stdin)
  234. p.stdin.close()
  235. return p.wait()
  236. def exec_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, env = None, **kwargs):
  237. """!Interface to os.execvpe(), but with the make_command() interface.
  238. @param prog GRASS module
  239. @param flags flags to be used (given as a string)
  240. @param overwrite True to enable overwriting the output (<tt>--o</tt>)
  241. @param quiet True to run quietly (<tt>--q</tt>)
  242. @param verbose True to run verbosely (<tt>--v</tt>)
  243. @param env directory with enviromental variables
  244. @param kwargs module's parameters
  245. """
  246. args = make_command(prog, flags, overwrite, quiet, verbose, **kwargs)
  247. if env == None:
  248. env = os.environ
  249. os.execvpe(prog, args, env)
  250. # interface to g.message
  251. def message(msg, flag = None):
  252. """!Display a message using `g.message`
  253. @param msg message to be displayed
  254. @param flag flags (given as string)
  255. """
  256. run_command("g.message", flags = flag, message = msg)
  257. def debug(msg, debug = 1):
  258. """!Display a debugging message using `g.message -d`
  259. @param msg debugging message to be displayed
  260. @param debug debug level (0-5)
  261. """
  262. run_command("g.message", flags = 'd', message = msg, debug = debug)
  263. def verbose(msg):
  264. """!Display a verbose message using `g.message -v`
  265. @param msg verbose message to be displayed
  266. """
  267. message(msg, flag = 'v')
  268. def info(msg):
  269. """!Display an informational message using `g.message -i`
  270. @param msg informational message to be displayed
  271. """
  272. message(msg, flag = 'i')
  273. def percent(i, n, s):
  274. """!Display a progress info message using `g.message -p`
  275. @code
  276. message(_("Percent complete..."))
  277. n = 100
  278. for i in range(n):
  279. percent(i, n, 1)
  280. percent(1, 1, 1)
  281. @endcode
  282. @param i current item
  283. @param n total number of items
  284. @param s increment size
  285. """
  286. message("%d %d %d" % (i, n, s), flag = 'p')
  287. def warning(msg):
  288. """!Display a warning message using `g.message -w`
  289. @param msg warning message to be displayed
  290. """
  291. message(msg, flag = 'w')
  292. def error(msg):
  293. """!Display an error message using `g.message -e`
  294. Raise exception when on_error is 'raise'.
  295. @param msg error message to be displayed
  296. """
  297. global raise_on_error
  298. if raise_on_error:
  299. raise ScriptError(msg)
  300. else:
  301. message(msg, flag = 'e')
  302. def fatal(msg):
  303. """!Display an error message using `g.message -e`, then abort
  304. @param msg error message to be displayed
  305. """
  306. error(msg)
  307. sys.exit(1)
  308. def set_raise_on_error(raise_exp = True):
  309. """!Define behaviour on error (error() called)
  310. @param raise_exp True to raise ScriptError instead of calling
  311. error()
  312. @return current status
  313. """
  314. global raise_on_error
  315. tmp_raise = raise_on_error
  316. raise_on_error = raise_exp
  317. # interface to g.parser
  318. def _parse_opts(lines):
  319. options = {}
  320. flags = {}
  321. for line in lines:
  322. line = line.rstrip('\r\n')
  323. if not line:
  324. break
  325. try:
  326. [var, val] = line.split('=', 1)
  327. except:
  328. raise SyntaxError("invalid output from g.parser: %s" % line)
  329. if var.startswith('flag_'):
  330. flags[var[5:]] = bool(int(val))
  331. elif var.startswith('opt_'):
  332. options[var[4:]] = val
  333. elif var in ['GRASS_OVERWRITE', 'GRASS_VERBOSE']:
  334. os.environ[var] = val
  335. else:
  336. raise SyntaxError("invalid output from g.parser: %s" % line)
  337. return (options, flags)
  338. def parser():
  339. """!Interface to g.parser, intended to be run from the top-level, e.g.:
  340. @code
  341. if __name__ == "__main__":
  342. options, flags = grass.parser()
  343. main()
  344. @endcode
  345. Thereafter, the global variables "options" and "flags" will be
  346. dictionaries containing option/flag values, keyed by lower-case
  347. option/flag names. The values in "options" are strings, those in
  348. "flags" are Python booleans.
  349. """
  350. if not os.getenv("GISBASE"):
  351. print >> sys.stderr, "You must be in GRASS GIS to run this program."
  352. sys.exit(1)
  353. cmdline = [basename(sys.argv[0])]
  354. cmdline += ['"' + arg + '"' for arg in sys.argv[1:]]
  355. os.environ['CMDLINE'] = ' '.join(cmdline)
  356. argv = sys.argv[:]
  357. name = argv[0]
  358. if not os.path.isabs(name):
  359. if os.sep in name or (os.altsep and os.altsep in name):
  360. argv[0] = os.path.abspath(name)
  361. else:
  362. argv[0] = os.path.join(sys.path[0], name)
  363. p = Popen(['g.parser', '-s'] + argv, stdout = PIPE)
  364. s = p.communicate()[0]
  365. lines = s.splitlines()
  366. if not lines or lines[0].rstrip('\r\n') != "@ARGS_PARSED@":
  367. sys.stdout.write(s)
  368. sys.exit(p.returncode)
  369. return _parse_opts(lines[1:])
  370. # interface to g.tempfile
  371. def tempfile(create = True):
  372. """!Returns the name of a temporary file, created with
  373. g.tempfile.
  374. @param create True to create a file
  375. @return path to a tmp file
  376. """
  377. flags = ''
  378. if not create:
  379. flags += 'd'
  380. return read_command("g.tempfile", flags = flags, pid = os.getpid()).strip()
  381. def tempdir():
  382. """!Returns the name of a temporary dir, created with g.tempfile."""
  383. tmp = tempfile(create = False)
  384. os.mkdir(tmp)
  385. return tmp
  386. # key-value parsers
  387. def parse_key_val(s, sep = '=', dflt = None, val_type = None, vsep = None):
  388. """!Parse a string into a dictionary, where entries are separated
  389. by newlines and the key and value are separated by `sep' (default: `=')
  390. @param s string to be parsed
  391. @param sep key/value separator
  392. @param dflt default value to be used
  393. @param val_type value type (None for no cast)
  394. @param vsep vertical separator (default os.linesep)
  395. @return parsed input (dictionary of keys/values)
  396. """
  397. result = {}
  398. if not s:
  399. return result
  400. if vsep:
  401. lines = s.split(vsep)
  402. try:
  403. lines.remove('\n')
  404. except ValueError:
  405. pass
  406. else:
  407. lines = s.splitlines()
  408. for line in lines:
  409. kv = line.split(sep, 1)
  410. k = kv[0].strip()
  411. if len(kv) > 1:
  412. v = kv[1]
  413. else:
  414. v = dflt
  415. if val_type:
  416. result[k] = val_type(v)
  417. else:
  418. result[k] = v
  419. return result
  420. # interface to g.gisenv
  421. def gisenv():
  422. """!Returns the output from running g.gisenv (with no arguments), as a
  423. dictionary. Example:
  424. \code
  425. >>> env = grass.gisenv()
  426. >>> print env['GISDBASE']
  427. /opt/grass-data
  428. \endcode
  429. @return list of GRASS variables
  430. """
  431. s = read_command("g.gisenv", flags='n')
  432. return parse_key_val(s)
  433. # interface to g.region
  434. def region():
  435. """!Returns the output from running "g.region -g", as a
  436. dictionary. Example:
  437. \code
  438. >>> region = grass.region()
  439. >>> [region[key] for key in "nsew"]
  440. [228500.0, 215000.0, 645000.0, 630000.0]
  441. >>> (region['nsres'], region['ewres'])
  442. (10.0, 10.0)
  443. \endcode
  444. @return dictionary of region values
  445. """
  446. s = read_command("g.region", flags='g')
  447. reg = parse_key_val(s, val_type = float)
  448. for k in ['rows', 'cols']:
  449. reg[k] = int(reg[k])
  450. return reg
  451. def use_temp_region():
  452. """!Copies the current region to a temporary region with "g.region save=",
  453. then sets WIND_OVERRIDE to refer to that region. Installs an atexit
  454. handler to delete the temporary region upon termination.
  455. """
  456. name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
  457. run_command("g.region", save = name, overwrite = True)
  458. os.environ['WIND_OVERRIDE'] = name
  459. atexit.register(del_temp_region)
  460. def del_temp_region():
  461. """!Unsets WIND_OVERRIDE and removes any region named by it."""
  462. try:
  463. name = os.environ.pop('WIND_OVERRIDE')
  464. run_command("g.remove", quiet = True, region = name)
  465. except:
  466. pass
  467. # interface to g.findfile
  468. def find_file(name, element = 'cell', mapset = None):
  469. """!Returns the output from running g.findfile as a
  470. dictionary. Example:
  471. \code
  472. >>> result = grass.find_file('fields', element = 'vector')
  473. >>> print result['fullname']
  474. fields@PERMANENT
  475. >>> print result['file']
  476. /opt/grass-data/spearfish60/PERMANENT/vector/fields
  477. \endcode
  478. @param name file name
  479. @param element element type (default 'cell')
  480. @param mapset mapset name (default all mapsets in search path)
  481. @return parsed output of g.findfile
  482. """
  483. s = read_command("g.findfile", flags='n', element = element, file = name, mapset = mapset)
  484. return parse_key_val(s)
  485. # interface to g.list
  486. def list_grouped(type, check_search_path = True):
  487. """!List elements grouped by mapsets.
  488. Returns the output from running g.list, as a dictionary where the
  489. keys are mapset names and the values are lists of maps in that
  490. mapset. Example:
  491. @code
  492. >>> grass.list_grouped('rast')['PERMANENT']
  493. ['aspect', 'erosion1', 'quads', 'soils', 'strm.dist', ...
  494. @endcode
  495. @param type element type (rast, vect, rast3d, region, ...)
  496. @param check_search_path True to add mapsets for the search path with no found elements
  497. @return directory of mapsets/elements
  498. """
  499. dashes_re = re.compile("^----+$")
  500. mapset_re = re.compile("<(.*)>")
  501. result = {}
  502. if check_search_path:
  503. for mapset in mapsets(search_path = True):
  504. result[mapset] = []
  505. mapset = None
  506. for line in read_command("g.list", type = type).splitlines():
  507. if line == "":
  508. continue
  509. if dashes_re.match(line):
  510. continue
  511. m = mapset_re.search(line)
  512. if m:
  513. mapset = m.group(1)
  514. if mapset not in result.keys():
  515. result[mapset] = []
  516. continue
  517. if mapset:
  518. result[mapset].extend(line.split())
  519. return result
  520. def _concat(xs):
  521. result = []
  522. for x in xs:
  523. result.extend(x)
  524. return result
  525. def list_pairs(type):
  526. """!List of elements as tuples.
  527. Returns the output from running g.list, as a list of (map, mapset)
  528. pairs. Example:
  529. @code
  530. >>> grass.list_pairs('rast')
  531. [('aspect', 'PERMANENT'), ('erosion1', 'PERMANENT'), ('quads', 'PERMANENT'), ...
  532. @endcode
  533. @param type element type (rast, vect, rast3d, region, ...)
  534. @return list of tuples (map, mapset)
  535. """
  536. return _concat([[(map, mapset) for map in maps]
  537. for mapset, maps in list_grouped(type).iteritems()])
  538. def list_strings(type):
  539. """!List of elements as strings.
  540. Returns the output from running g.list, as a list of qualified
  541. names. Example:
  542. @code
  543. >>> grass.list_strings('rast')
  544. ['aspect@PERMANENT', 'erosion1@PERMANENT', 'quads@PERMANENT', 'soils@PERMANENT', ...
  545. @endcode
  546. @param type element type
  547. @return list of strings ('map@@mapset')
  548. """
  549. return ["%s@%s" % pair for pair in list_pairs(type)]
  550. # interface to g.mlist
  551. def mlist_grouped(type, pattern = None, check_search_path = True):
  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. @param check_search_path True to add mapsets for the search path with no found elements
  563. @return directory of mapsets/elements
  564. """
  565. result = {}
  566. if check_search_path:
  567. for mapset in mapsets(search_path = True):
  568. result[mapset] = []
  569. mapset = None
  570. for line in read_command("g.mlist", quiet = True, flags = "m",
  571. type = type, pattern = pattern).splitlines():
  572. try:
  573. name, mapset = line.split('@')
  574. except ValueError:
  575. warning(_("Invalid element '%s'") % line)
  576. continue
  577. if mapset in result:
  578. result[mapset].append(name)
  579. else:
  580. result[mapset] = [name, ]
  581. return result
  582. # color parsing
  583. named_colors = {
  584. "white": (1.00, 1.00, 1.00),
  585. "black": (0.00, 0.00, 0.00),
  586. "red": (1.00, 0.00, 0.00),
  587. "green": (0.00, 1.00, 0.00),
  588. "blue": (0.00, 0.00, 1.00),
  589. "yellow": (1.00, 1.00, 0.00),
  590. "magenta": (1.00, 0.00, 1.00),
  591. "cyan": (0.00, 1.00, 1.00),
  592. "aqua": (0.00, 0.75, 0.75),
  593. "grey": (0.75, 0.75, 0.75),
  594. "gray": (0.75, 0.75, 0.75),
  595. "orange": (1.00, 0.50, 0.00),
  596. "brown": (0.75, 0.50, 0.25),
  597. "purple": (0.50, 0.00, 1.00),
  598. "violet": (0.50, 0.00, 1.00),
  599. "indigo": (0.00, 0.50, 1.00)}
  600. def parse_color(val, dflt = None):
  601. """!Parses the string "val" as a GRASS colour, which can be either one of
  602. the named colours or an R:G:B tuple e.g. 255:255:255. Returns an
  603. (r,g,b) triple whose components are floating point values between 0
  604. and 1. Example:
  605. \code
  606. >>> grass.parse_color("red")
  607. (1.0, 0.0, 0.0)
  608. >>> grass.parse_color("255:0:0")
  609. (1.0, 0.0, 0.0)
  610. \endcode
  611. @param val color value
  612. @param dflt default color value
  613. @return tuple RGB
  614. """
  615. if val in named_colors:
  616. return named_colors[val]
  617. vals = val.split(':')
  618. if len(vals) == 3:
  619. return tuple(float(v) / 255 for v in vals)
  620. return dflt
  621. # check GRASS_OVERWRITE
  622. def overwrite():
  623. """!Return True if existing files may be overwritten"""
  624. owstr = 'GRASS_OVERWRITE'
  625. return owstr in os.environ and os.environ[owstr] != '0'
  626. # check GRASS_VERBOSE
  627. def verbosity():
  628. """!Return the verbosity level selected by GRASS_VERBOSE"""
  629. vbstr = os.getenv('GRASS_VERBOSE')
  630. if vbstr:
  631. return int(vbstr)
  632. else:
  633. return 2
  634. ## various utilities, not specific to GRASS
  635. # basename inc. extension stripping
  636. def basename(path, ext = None):
  637. """!Remove leading directory components and an optional extension
  638. from the specified path
  639. @param path path
  640. @param ext extension
  641. """
  642. name = os.path.basename(path)
  643. if not ext:
  644. return name
  645. fs = name.rsplit('.', 1)
  646. if len(fs) > 1 and fs[1].lower() == ext:
  647. name = fs[0]
  648. return name
  649. # find a program (replacement for "which")
  650. def find_program(pgm, args = []):
  651. """!Attempt to run a program, with optional arguments.
  652. @param pgm program name
  653. @param args list of arguments
  654. @return False if the attempt failed due to a missing executable
  655. @return True otherwise
  656. """
  657. nuldev = file(os.devnull, 'w+')
  658. try:
  659. ret = call([pgm] + args, stdin = nuldev, stdout = nuldev, stderr = nuldev)
  660. if ret == 0:
  661. found = True
  662. else:
  663. found = False
  664. except:
  665. found = False
  666. nuldev.close()
  667. return found
  668. # try to remove a file, without complaints
  669. def try_remove(path):
  670. """!Attempt to remove a file; no exception is generated if the
  671. attempt fails.
  672. @param path path to file to remove
  673. """
  674. try:
  675. os.remove(path)
  676. except:
  677. pass
  678. # try to remove a directory, without complaints
  679. def try_rmdir(path):
  680. """!Attempt to remove a directory; no exception is generated if the
  681. attempt fails.
  682. @param path path to directory to remove
  683. """
  684. try:
  685. os.rmdir(path)
  686. except:
  687. shutil.rmtree(path, ignore_errors = True)
  688. def float_or_dms(s):
  689. """!Convert DMS to float.
  690. @param s DMS value
  691. @return float value
  692. """
  693. return sum(float(x) / 60 ** n for (n, x) in enumerate(s.split(':')))
  694. # interface to g.mapsets
  695. def mapsets(search_path = False):
  696. """!List available mapsets
  697. @param searchPatch True to list mapsets only in search path
  698. @return list of mapsets
  699. """
  700. if search_path:
  701. flags = 'p'
  702. else:
  703. flags = 'l'
  704. mapsets = read_command('g.mapsets',
  705. flags = flags,
  706. fs = 'newline',
  707. quiet = True)
  708. if not mapsets:
  709. fatal(_("Unable to list mapsets"))
  710. return mapsets.splitlines()
  711. # interface to `g.proj -c`
  712. def create_location(dbase, location,
  713. epsg = None, proj4 = None, filename = None, wkt = None,
  714. datum = None, desc = None):
  715. """!Create new location
  716. Raise ScriptError on error.
  717. @param dbase path to GRASS database
  718. @param location location name to create
  719. @param epgs if given create new location based on EPSG code
  720. @param proj4 if given create new location based on Proj4 definition
  721. @param filename if given create new location based on georeferenced file
  722. @param wkt if given create new location based on WKT definition (path to PRJ file)
  723. @param datum datum transformation parameters (used for epsg and proj4)
  724. @param desc description of the location (creates MYNAME file)
  725. """
  726. gisdbase = None
  727. if epsg or proj4 or filename or wkt:
  728. gisdbase = gisenv()['GISDBASE']
  729. run_command('g.gisenv',
  730. set = 'GISDBASE=%s' % dbase)
  731. if not os.path.exists(dbase):
  732. os.mkdir(dbase)
  733. kwargs = dict()
  734. if datum:
  735. kwargs['datum'] = datum
  736. if epsg:
  737. ps = pipe_command('g.proj',
  738. quiet = True,
  739. epsg = epsg,
  740. location = location,
  741. stderr = PIPE,
  742. **kwargs)
  743. elif proj4:
  744. ps = pipe_command('g.proj',
  745. quiet = True,
  746. proj4 = proj4,
  747. location = location,
  748. stderr = PIPE,
  749. **kwargs)
  750. elif filename:
  751. ps = pipe_command('g.proj',
  752. quiet = True,
  753. georef = filename,
  754. location = location,
  755. stderr = PIPE)
  756. elif wkt:
  757. ps = pipe_command('g.proj',
  758. quiet = True,
  759. wkt = wkt,
  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. print version()
  826. {'date': '2011', 'libgis_date': '2011-08-13 01:14:30 +0200 (Sat, 13 Aug 2011)',
  827. 'version': '7.0.svn', 'libgis_revision': '47604', 'revision': '47963'}
  828. @endcode
  829. """
  830. data = parse_command('g.version',
  831. flags = 'rg')
  832. for k, v in data.iteritems():
  833. data[k.strip()] = v.replace('"', '').strip()
  834. return data
  835. # get debug_level
  836. if find_program('g.gisenv', ['--help']):
  837. debug_level = int(gisenv().get('DEBUG', 0))