core.py 29 KB

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