core.py 28 KB

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