core.py 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334
  1. """!@package grass.script.core
  2. @brief GRASS Python scripting module (core functions)
  3. Core functions to be used in Python scripts.
  4. Usage:
  5. @code
  6. from grass.script import core as grass
  7. grass.parser()
  8. ...
  9. @endcode
  10. (C) 2008-2011 by the GRASS Development Team
  11. This program is free software under the GNU General Public
  12. License (>=v2). Read the file COPYING that comes with GRASS
  13. for details.
  14. @author Glynn Clements
  15. @author Martin Landa <landa.martin gmail.com>
  16. @author Michael Barton <michael.barton asu.edu>
  17. """
  18. import os
  19. import sys
  20. import types
  21. import re
  22. import atexit
  23. import subprocess
  24. import shutil
  25. import locale
  26. import codecs
  27. # i18N
  28. import gettext
  29. gettext.install('grasslibs', os.path.join(os.getenv("GISBASE"), 'locale'))
  30. # subprocess wrapper that uses shell on Windows
  31. class Popen(subprocess.Popen):
  32. def __init__(self, args, bufsize = 0, executable = None,
  33. stdin = None, stdout = None, stderr = None,
  34. preexec_fn = None, close_fds = False, shell = None,
  35. cwd = None, env = None, universal_newlines = False,
  36. startupinfo = None, creationflags = 0):
  37. if shell == None:
  38. shell = (sys.platform == "win32")
  39. subprocess.Popen.__init__(self, args, bufsize, executable,
  40. stdin, stdout, stderr,
  41. preexec_fn, close_fds, shell,
  42. cwd, env, universal_newlines,
  43. startupinfo, creationflags)
  44. PIPE = subprocess.PIPE
  45. STDOUT = subprocess.STDOUT
  46. class ScriptError(Exception):
  47. def __init__(self, msg):
  48. self.value = msg
  49. def __str__(self):
  50. return self.value
  51. raise_on_error = False # raise exception instead of calling fatal()
  52. debug_level = 0 # DEBUG level
  53. def call(*args, **kwargs):
  54. return Popen(*args, **kwargs).wait()
  55. # GRASS-oriented interface to subprocess module
  56. _popen_args = ["bufsize", "executable", "stdin", "stdout", "stderr",
  57. "preexec_fn", "close_fds", "cwd", "env",
  58. "universal_newlines", "startupinfo", "creationflags"]
  59. def decode(string):
  60. enc = locale.getdefaultlocale()[1]
  61. if enc:
  62. return string.decode(enc)
  63. return string
  64. def _make_val(val):
  65. if isinstance(val, types.StringType) or \
  66. isinstance(val, types.UnicodeType):
  67. return val
  68. if isinstance(val, types.ListType):
  69. return ",".join(map(_make_val, val))
  70. if isinstance(val, types.TupleType):
  71. return _make_val(list(val))
  72. return str(val)
  73. def make_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, **options):
  74. """!Return a list of strings suitable for use as the args parameter to
  75. Popen() or call(). Example:
  76. @code
  77. >>> grass.make_command("g.message", flags = 'w', message = 'this is a warning')
  78. ['g.message', '-w', 'message=this is a warning']
  79. @endcode
  80. @param prog GRASS module
  81. @param flags flags to be used (given as a string)
  82. @param overwrite True to enable overwriting the output (<tt>--o</tt>)
  83. @param quiet True to run quietly (<tt>--q</tt>)
  84. @param verbose True to run verbosely (<tt>--v</tt>)
  85. @param options module's parameters
  86. @return list of arguments
  87. """
  88. args = [prog]
  89. if overwrite:
  90. args.append("--o")
  91. if quiet:
  92. args.append("--q")
  93. if verbose:
  94. args.append("--v")
  95. if flags:
  96. if '-' in flags:
  97. raise ScriptError("'-' is not a valid flag")
  98. args.append("-%s" % flags)
  99. for opt, val in options.iteritems():
  100. if val != None:
  101. if opt[0] == '_':
  102. opt = opt[1:]
  103. args.append("%s=%s" % (opt, _make_val(val)))
  104. return args
  105. def start_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, **kwargs):
  106. """!Returns a Popen object with the command created by make_command.
  107. Accepts any of the arguments which Popen() accepts apart from "args"
  108. and "shell".
  109. \code
  110. >>> p = grass.start_command("g.gisenv", stdout = subprocess.PIPE)
  111. >>> print p
  112. <subprocess.Popen object at 0xb7c12f6c>
  113. >>> print p.communicate()[0]
  114. GISDBASE='/opt/grass-data';
  115. LOCATION_NAME='spearfish60';
  116. MAPSET='glynn';
  117. GRASS_DB_ENCODING='ascii';
  118. GUI='text';
  119. MONITOR='x0';
  120. \endcode
  121. @param prog GRASS module
  122. @param flags flags to be used (given as a string)
  123. @param overwrite True to enable overwriting the output (<tt>--o</tt>)
  124. @param quiet True to run quietly (<tt>--q</tt>)
  125. @param verbose True to run verbosely (<tt>--v</tt>)
  126. @param kwargs module's parameters
  127. @return Popen object
  128. """
  129. options = {}
  130. popts = {}
  131. for opt, val in kwargs.iteritems():
  132. if opt in _popen_args:
  133. popts[opt] = val
  134. else:
  135. options[opt] = val
  136. args = make_command(prog, flags, overwrite, quiet, verbose, **options)
  137. global debug_level
  138. if debug_level > 0:
  139. sys.stderr.write("D1/%d: %s.start_command(): %s\n" % (debug_level, __name__, ' '.join(args)))
  140. sys.stderr.flush()
  141. return Popen(args, **popts)
  142. def run_command(*args, **kwargs):
  143. """!Passes all arguments to start_command(), then waits for the process to
  144. complete, returning its exit code. Similar to subprocess.call(), but
  145. with the make_command() interface.
  146. @param args list of unnamed arguments (see start_command() for details)
  147. @param kwargs list of named arguments (see start_command() for details)
  148. @return exit code (0 for success)
  149. """
  150. ps = start_command(*args, **kwargs)
  151. return ps.wait()
  152. def pipe_command(*args, **kwargs):
  153. """!Passes all arguments to start_command(), but also adds
  154. "stdout = PIPE". Returns the Popen object.
  155. \code
  156. >>> p = grass.pipe_command("g.gisenv")
  157. >>> print p
  158. <subprocess.Popen object at 0xb7c12f6c>
  159. >>> print p.communicate()[0]
  160. GISDBASE='/opt/grass-data';
  161. LOCATION_NAME='spearfish60';
  162. MAPSET='glynn';
  163. GRASS_DB_ENCODING='ascii';
  164. GUI='text';
  165. MONITOR='x0';
  166. \endcode
  167. @param args list of unnamed arguments (see start_command() for details)
  168. @param kwargs list of named arguments (see start_command() for details)
  169. @return Popen object
  170. """
  171. kwargs['stdout'] = PIPE
  172. return start_command(*args, **kwargs)
  173. def feed_command(*args, **kwargs):
  174. """!Passes all arguments to start_command(), but also adds
  175. "stdin = PIPE". Returns the Popen object.
  176. @param args list of unnamed arguments (see start_command() for details)
  177. @param kwargs list of named arguments (see start_command() for details)
  178. @return Popen object
  179. """
  180. kwargs['stdin'] = PIPE
  181. return start_command(*args, **kwargs)
  182. def read_command(*args, **kwargs):
  183. """!Passes all arguments to pipe_command, then waits for the process to
  184. complete, returning its stdout (i.e. similar to shell `backticks`).
  185. @param args list of unnamed arguments (see start_command() for details)
  186. @param kwargs list of named arguments (see start_command() for details)
  187. @return stdout
  188. """
  189. ps = pipe_command(*args, **kwargs)
  190. return ps.communicate()[0]
  191. def parse_command(*args, **kwargs):
  192. """!Passes all arguments to read_command, then parses the output
  193. by parse_key_val().
  194. Parsing function can be optionally given by <em>parse</em> parameter
  195. including its arguments, e.g.
  196. @code
  197. parse_command(..., parse = (grass.parse_key_val, { 'sep' : ':' }))
  198. @endcode
  199. or you can simply define <em>delimiter</em>
  200. @code
  201. parse_command(..., delimiter = ':')
  202. @endcode
  203. @param args list of unnamed arguments (see start_command() for details)
  204. @param kwargs list of named arguments (see start_command() for details)
  205. @return parsed module output
  206. """
  207. parse = None
  208. parse_args = {}
  209. if 'parse' in kwargs:
  210. if type(kwargs['parse']) is types.TupleType:
  211. parse = kwargs['parse'][0]
  212. parse_args = kwargs['parse'][1]
  213. del kwargs['parse']
  214. if 'delimiter' in kwargs:
  215. parse_args = { 'sep' : kwargs['delimiter'] }
  216. del kwargs['delimiter']
  217. if not parse:
  218. parse = parse_key_val # use default fn
  219. res = read_command(*args, **kwargs)
  220. return parse(res, **parse_args)
  221. def write_command(*args, **kwargs):
  222. """!Passes all arguments to feed_command, with the string specified
  223. by the 'stdin' argument fed to the process' stdin.
  224. @param args list of unnamed arguments (see start_command() for details)
  225. @param kwargs list of named arguments (see start_command() for details)
  226. @return return code
  227. """
  228. stdin = kwargs['stdin']
  229. p = feed_command(*args, **kwargs)
  230. p.stdin.write(stdin)
  231. p.stdin.close()
  232. return p.wait()
  233. def exec_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, env = None, **kwargs):
  234. """!Interface to os.execvpe(), but with the make_command() interface.
  235. @param prog GRASS module
  236. @param flags flags to be used (given as a string)
  237. @param overwrite True to enable overwriting the output (<tt>--o</tt>)
  238. @param quiet True to run quietly (<tt>--q</tt>)
  239. @param verbose True to run verbosely (<tt>--v</tt>)
  240. @param env directory with environmental variables
  241. @param kwargs module's parameters
  242. """
  243. args = make_command(prog, flags, overwrite, quiet, verbose, **kwargs)
  244. if env == None:
  245. env = os.environ
  246. os.execvpe(prog, args, env)
  247. # interface to g.message
  248. def message(msg, flag = None):
  249. """!Display a message using `g.message`
  250. @param msg message to be displayed
  251. @param flag flags (given as string)
  252. """
  253. run_command("g.message", flags = flag, message = msg)
  254. def debug(msg, debug = 1):
  255. """!Display a debugging message using `g.message -d`
  256. @param msg debugging message to be displayed
  257. @param debug debug level (0-5)
  258. """
  259. run_command("g.message", flags = 'd', message = msg, debug = debug)
  260. def verbose(msg):
  261. """!Display a verbose message using `g.message -v`
  262. @param msg verbose message to be displayed
  263. """
  264. message(msg, flag = 'v')
  265. def info(msg):
  266. """!Display an informational message using `g.message -i`
  267. @param msg informational message to be displayed
  268. """
  269. message(msg, flag = 'i')
  270. def percent(i, n, s):
  271. """!Display a progress info message using `g.message -p`
  272. @code
  273. message(_("Percent complete..."))
  274. n = 100
  275. for i in range(n):
  276. percent(i, n, 1)
  277. percent(1, 1, 1)
  278. @endcode
  279. @param i current item
  280. @param n total number of items
  281. @param s increment size
  282. """
  283. message("%d %d %d" % (i, n, s), flag = 'p')
  284. def warning(msg):
  285. """!Display a warning message using `g.message -w`
  286. @param msg warning message to be displayed
  287. """
  288. message(msg, flag = 'w')
  289. def error(msg):
  290. """!Display an error message using `g.message -e`
  291. Raise exception when on_error is 'raise'.
  292. @param msg error message to be displayed
  293. """
  294. global raise_on_error
  295. if raise_on_error:
  296. raise ScriptError(msg)
  297. else:
  298. message(msg, flag = 'e')
  299. def fatal(msg):
  300. """!Display an error message using `g.message -e`, then abort
  301. @param msg error message to be displayed
  302. """
  303. error(msg)
  304. sys.exit(1)
  305. def set_raise_on_error(raise_exp = True):
  306. """!Define behaviour on error (error() called)
  307. @param raise_exp True to raise ScriptError instead of calling
  308. error()
  309. @return current status
  310. """
  311. global raise_on_error
  312. tmp_raise = raise_on_error
  313. raise_on_error = raise_exp
  314. # interface to g.parser
  315. def _parse_opts(lines):
  316. options = {}
  317. flags = {}
  318. for line in lines:
  319. line = line.rstrip('\r\n')
  320. if not line:
  321. break
  322. try:
  323. [var, val] = line.split('=', 1)
  324. except:
  325. raise SyntaxError("invalid output from g.parser: %s" % line)
  326. if var.startswith('flag_'):
  327. flags[var[5:]] = bool(int(val))
  328. elif var.startswith('opt_'):
  329. options[var[4:]] = val
  330. elif var in ['GRASS_OVERWRITE', 'GRASS_VERBOSE']:
  331. os.environ[var] = val
  332. else:
  333. raise SyntaxError("invalid output from g.parser: %s" % line)
  334. return (options, flags)
  335. def parser():
  336. """!Interface to g.parser, intended to be run from the top-level, e.g.:
  337. @code
  338. if __name__ == "__main__":
  339. options, flags = grass.parser()
  340. main()
  341. @endcode
  342. Thereafter, the global variables "options" and "flags" will be
  343. dictionaries containing option/flag values, keyed by lower-case
  344. option/flag names. The values in "options" are strings, those in
  345. "flags" are Python booleans.
  346. """
  347. if not os.getenv("GISBASE"):
  348. print >> sys.stderr, "You must be in GRASS GIS to run this program."
  349. sys.exit(1)
  350. cmdline = [basename(sys.argv[0])]
  351. cmdline += ['"' + arg + '"' for arg in sys.argv[1:]]
  352. os.environ['CMDLINE'] = ' '.join(cmdline)
  353. argv = sys.argv[:]
  354. name = argv[0]
  355. if not os.path.isabs(name):
  356. if os.sep in name or (os.altsep and os.altsep in name):
  357. argv[0] = os.path.abspath(name)
  358. else:
  359. argv[0] = os.path.join(sys.path[0], name)
  360. p = Popen(['g.parser', '-s'] + argv, stdout = PIPE)
  361. s = p.communicate()[0]
  362. lines = s.splitlines()
  363. if not lines or lines[0].rstrip('\r\n') != "@ARGS_PARSED@":
  364. sys.stdout.write(s)
  365. sys.exit(p.returncode)
  366. return _parse_opts(lines[1:])
  367. # interface to g.tempfile
  368. def tempfile(create = True):
  369. """!Returns the name of a temporary file, created with
  370. g.tempfile.
  371. @param create True to create a file
  372. @return path to a tmp file
  373. """
  374. flags = ''
  375. if not create:
  376. flags += 'd'
  377. return read_command("g.tempfile", flags = flags, pid = os.getpid()).strip()
  378. def tempdir():
  379. """!Returns the name of a temporary dir, created with g.tempfile."""
  380. tmp = tempfile(create = False)
  381. os.mkdir(tmp)
  382. return tmp
  383. class KeyValue(dict):
  384. """A general-purpose key-value store.
  385. KeyValue is a subclass of dict, but also allows entries to be read and
  386. written using attribute syntax. Example:
  387. \code
  388. >>> region = grass.region()
  389. >>> region['rows']
  390. 477
  391. >>> region.rows
  392. 477
  393. \endcode
  394. """
  395. def __getattr__(self, key):
  396. return self[key]
  397. def __setattr__(self, key, value):
  398. self[key] = value
  399. # key-value parsers
  400. def parse_key_val(s, sep = '=', dflt = None, val_type = None, vsep = None):
  401. """!Parse a string into a dictionary, where entries are separated
  402. by newlines and the key and value are separated by `sep' (default: `=')
  403. @param s string to be parsed
  404. @param sep key/value separator
  405. @param dflt default value to be used
  406. @param val_type value type (None for no cast)
  407. @param vsep vertical separator (default os.linesep)
  408. @return parsed input (dictionary of keys/values)
  409. """
  410. result = KeyValue()
  411. if not s:
  412. return result
  413. if vsep:
  414. lines = s.split(vsep)
  415. try:
  416. lines.remove('\n')
  417. except ValueError:
  418. pass
  419. else:
  420. lines = s.splitlines()
  421. for line in lines:
  422. kv = line.split(sep, 1)
  423. k = kv[0].strip()
  424. if len(kv) > 1:
  425. v = kv[1].strip()
  426. else:
  427. v = dflt
  428. if val_type:
  429. result[k] = val_type(v)
  430. else:
  431. result[k] = v
  432. return result
  433. def _text_to_key_value_dict(filename, sep=":", val_sep=","):
  434. """
  435. !Convert a key-value text file, where entries are separated
  436. by newlines and the key and value are separated by `sep',
  437. into a key-value dictionary and discover/use the correct
  438. data types (float, int or string) for values.
  439. @param filename The name or name and path of the text file to convert
  440. @param sep The character that separates the keys and values, default is ":"
  441. @param val_sep The character that separates the values of a single key, default is ","
  442. @return The dictionary
  443. A text file with this content:
  444. \code
  445. a: Hello
  446. b: 1.0
  447. c: 1,2,3,4,5
  448. d : hello,8,0.1
  449. \endcode
  450. Will be represented as this dictionary:
  451. \code
  452. {'a': ['Hello'], 'c': [1, 2, 3, 4, 5], 'b': [1.0], 'd': ['hello', 8, 0.1]}
  453. \endcode
  454. """
  455. text = open(filename, "r").readlines()
  456. kvdict = KeyValue()
  457. for line in text:
  458. if line.find(sep) >= 0:
  459. key, value = line.split(sep)
  460. key = key.strip()
  461. value = value.strip()
  462. else:
  463. # Jump over empty values
  464. continue
  465. values = value.split(val_sep)
  466. value_list = []
  467. for value in values:
  468. not_float = False
  469. not_int = False
  470. # Convert values into correct types
  471. # We first try integer then float
  472. try:
  473. value_converted = int(value)
  474. except:
  475. not_int = True
  476. if not_int:
  477. try:
  478. value_converted = float(value)
  479. except:
  480. not_float = True
  481. if not_int and not_float:
  482. value_converted = value.strip()
  483. value_list.append(value_converted)
  484. kvdict[key] = value_list
  485. return kvdict
  486. def compare_key_value_text_files(filename_a, filename_b, sep=":", val_sep=",", precision=0.000001):
  487. """
  488. !Compare two key-value text files that may contain projection parameter
  489. @param filename_a The name of the first key-value text file
  490. @param filenmae_b The name of the second key-value text file
  491. @param sep The character that separates the keys and values, default is ":"
  492. @param val_sep The character that separates the values of a single key, default is ","
  493. @param precision The precision with which the floating point values are compares
  494. if abs(a - b) > precision : return False
  495. @return True if full or almost identical, False if different
  496. This method will print a warning in case keys that are present in the first file
  497. are not present in the second one.
  498. The comparison method tries to convert the values into there native format (float, int or string)
  499. to allow correct comparison.
  500. An example key-value text file may have this content:
  501. \code
  502. a: Hello
  503. b: 1.0
  504. c: 1,2,3,4,5
  505. d : hello,8,0.1
  506. \endcode
  507. """
  508. dict_a = _text_to_key_value_dict(filename_a, sep)
  509. dict_b = _text_to_key_value_dict(filename_b, sep)
  510. missing_keys = 0
  511. # We compare matching keys
  512. for key in dict_a.keys():
  513. if dict_b.has_key(key):
  514. # Floating point values must be handled separately
  515. if isinstance(dict_a[key], float) and isinstance(dict_b[key], float):
  516. if abs(dict_a[key] - dict_b[key]) > precision:
  517. return False
  518. elif isinstance(dict_a[key], float) or isinstance(dict_b[key], float):
  519. return False
  520. else:
  521. if dict_a[key] != dict_b[key]:
  522. return False
  523. else:
  524. missing_keys += 1
  525. if missing_keys == len(dict_a):
  526. return False
  527. if missing_keys > 0:
  528. grass.warning(_("Several keys (%i out of %i) are missing in the target file")%(missing_keys, len(dict_a)))
  529. return True
  530. # interface to g.gisenv
  531. def gisenv():
  532. """!Returns the output from running g.gisenv (with no arguments), as a
  533. dictionary. Example:
  534. \code
  535. >>> env = grass.gisenv()
  536. >>> print env['GISDBASE']
  537. /opt/grass-data
  538. \endcode
  539. @return list of GRASS variables
  540. """
  541. s = read_command("g.gisenv", flags='n')
  542. return parse_key_val(s)
  543. # interface to g.region
  544. def locn_is_latlong():
  545. """!Tests if location is lat/long. Value is obtained
  546. by checking the "g.region -p" projection code.
  547. @return True for a lat/long region, False otherwise
  548. """
  549. s = read_command("g.region", flags='p')
  550. kv = parse_key_val(s, ':')
  551. if kv['projection'].split(' ')[1] == '3':
  552. return True
  553. else:
  554. return False
  555. def region(region3d = False):
  556. """!Returns the output from running "g.region -g", as a
  557. dictionary. Example:
  558. \param region3d True to get 3D region
  559. \code
  560. >>> region = grass.region()
  561. >>> [region[key] for key in "nsew"]
  562. [228500.0, 215000.0, 645000.0, 630000.0]
  563. >>> (region['nsres'], region['ewres'])
  564. (10.0, 10.0)
  565. \endcode
  566. @return dictionary of region values
  567. """
  568. flgs = 'g'
  569. if region3d:
  570. flgs += '3'
  571. s = read_command("g.region", flags = flgs)
  572. reg = parse_key_val(s, val_type = float)
  573. for k in ['rows', 'cols', 'cells',
  574. 'rows3', 'cols3', 'cells3', 'depths']:
  575. if k not in reg:
  576. continue
  577. reg[k] = int(reg[k])
  578. return reg
  579. def region_env(region3d = False,
  580. **kwargs):
  581. """!Returns region settings as a string which can used as
  582. GRASS_REGION environmental variable.
  583. If no 'kwargs' are given then the current region is used. Note
  584. that this function doesn't modify the current region!
  585. See also use_temp_region() for alternative method how to define
  586. temporary region used for raster-based computation.
  587. \param region3d True to get 3D region
  588. \param kwargs g.region's parameters like 'rast', 'vect' or 'region'
  589. \code
  590. os.environ['GRASS_REGION'] = grass.region_env(region = 'detail')
  591. grass.mapcalc('map = 1', overwrite = True)
  592. os.environ.pop('GRASS_REGION')
  593. \endcode
  594. @return string with region values
  595. @return empty string on error
  596. """
  597. # read proj/zone from WIND file
  598. env = gisenv()
  599. windfile = os.path.join (env['GISDBASE'], env['LOCATION_NAME'],
  600. env['MAPSET'], "WIND")
  601. fd = open(windfile, "r")
  602. grass_region = ''
  603. for line in fd.readlines():
  604. key, value = map(lambda x: x.strip(), line.split(":", 1))
  605. if kwargs and key not in ('proj', 'zone'):
  606. continue
  607. if not kwargs and not region3d and \
  608. key in ('top', 'bottom', 'cols3', 'rows3',
  609. 'depths', 'e-w resol3', 'n-s resol3', 't-b resol'):
  610. continue
  611. grass_region += '%s: %s;' % (key, value)
  612. if not kwargs: # return current region
  613. return grass_region
  614. # read other values from `g.region -g`
  615. flgs = 'ug'
  616. if region3d:
  617. flgs += '3'
  618. s = read_command('g.region', flags = flgs, **kwargs)
  619. if not s:
  620. return ''
  621. reg = parse_key_val(s)
  622. kwdata = [('north', 'n'),
  623. ('south', 's'),
  624. ('east', 'e'),
  625. ('west', 'w'),
  626. ('cols', 'cols'),
  627. ('rows', 'rows'),
  628. ('e-w resol', 'ewres'),
  629. ('n-s resol', 'nsres')]
  630. if region3d:
  631. kwdata += [('top', 't'),
  632. ('bottom', 'b'),
  633. ('cols3', 'cols3'),
  634. ('rows3', 'rows3'),
  635. ('depths', 'depths'),
  636. ('e-w resol3', 'ewres3'),
  637. ('n-s resol3', 'nsres3'),
  638. ('t-b resol', 'tbres')]
  639. for wkey, rkey in kwdata:
  640. grass_region += '%s: %s;' % (wkey, reg[rkey])
  641. return grass_region
  642. def use_temp_region():
  643. """!Copies the current region to a temporary region with "g.region save=",
  644. then sets WIND_OVERRIDE to refer to that region. Installs an atexit
  645. handler to delete the temporary region upon termination.
  646. """
  647. name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
  648. run_command("g.region", save = name, overwrite = True)
  649. os.environ['WIND_OVERRIDE'] = name
  650. atexit.register(del_temp_region)
  651. def del_temp_region():
  652. """!Unsets WIND_OVERRIDE and removes any region named by it."""
  653. try:
  654. name = os.environ.pop('WIND_OVERRIDE')
  655. run_command("g.remove", quiet = True, region = name)
  656. except:
  657. pass
  658. # interface to g.findfile
  659. def find_file(name, element = 'cell', mapset = None):
  660. """!Returns the output from running g.findfile as a
  661. dictionary. Example:
  662. \code
  663. >>> result = grass.find_file('fields', element = 'vector')
  664. >>> print result['fullname']
  665. fields@PERMANENT
  666. >>> print result['file']
  667. /opt/grass-data/spearfish60/PERMANENT/vector/fields
  668. \endcode
  669. @param name file name
  670. @param element element type (default 'cell')
  671. @param mapset mapset name (default all mapsets in search path)
  672. @return parsed output of g.findfile
  673. """
  674. if element == 'raster' or element == 'rast':
  675. verbose(_('Element type should be "cell" and not "%s"') % element)
  676. element = 'cell'
  677. s = read_command("g.findfile", flags='n', element = element, file = name, mapset = mapset)
  678. return parse_key_val(s)
  679. # interface to g.list
  680. def list_grouped(type, check_search_path = True):
  681. """!List elements grouped by mapsets.
  682. Returns the output from running g.list, as a dictionary where the
  683. keys are mapset names and the values are lists of maps in that
  684. mapset. Example:
  685. @code
  686. >>> grass.list_grouped('rast')['PERMANENT']
  687. ['aspect', 'erosion1', 'quads', 'soils', 'strm.dist', ...
  688. @endcode
  689. @param type element type (rast, vect, rast3d, region, ...)
  690. @param check_search_path True to add mapsets for the search path with no found elements
  691. @return directory of mapsets/elements
  692. """
  693. if type == 'raster' or type == 'cell':
  694. verbose(_('Element type should be "rast" and not "%s"') % element)
  695. type = 'rast'
  696. dashes_re = re.compile("^----+$")
  697. mapset_re = re.compile("<(.*)>")
  698. result = {}
  699. if check_search_path:
  700. for mapset in mapsets(search_path = True):
  701. result[mapset] = []
  702. mapset = None
  703. for line in read_command("g.list", type = type).splitlines():
  704. if line == "":
  705. continue
  706. if dashes_re.match(line):
  707. continue
  708. m = mapset_re.search(line)
  709. if m:
  710. mapset = m.group(1)
  711. if mapset not in result.keys():
  712. result[mapset] = []
  713. continue
  714. if mapset:
  715. result[mapset].extend(line.split())
  716. return result
  717. def _concat(xs):
  718. result = []
  719. for x in xs:
  720. result.extend(x)
  721. return result
  722. def list_pairs(type):
  723. """!List of elements as tuples.
  724. Returns the output from running g.list, as a list of (map, mapset)
  725. pairs. Example:
  726. @code
  727. >>> grass.list_pairs('rast')
  728. [('aspect', 'PERMANENT'), ('erosion1', 'PERMANENT'), ('quads', 'PERMANENT'), ...
  729. @endcode
  730. @param type element type (rast, vect, rast3d, region, ...)
  731. @return list of tuples (map, mapset)
  732. """
  733. return _concat([[(map, mapset) for map in maps]
  734. for mapset, maps in list_grouped(type).iteritems()])
  735. def list_strings(type):
  736. """!List of elements as strings.
  737. Returns the output from running g.list, as a list of qualified
  738. names. Example:
  739. @code
  740. >>> grass.list_strings('rast')
  741. ['aspect@PERMANENT', 'erosion1@PERMANENT', 'quads@PERMANENT', 'soils@PERMANENT', ...
  742. @endcode
  743. @param type element type
  744. @return list of strings ('map@@mapset')
  745. """
  746. return ["%s@%s" % pair for pair in list_pairs(type)]
  747. # interface to g.mlist
  748. def mlist_strings(type, pattern = None, mapset = None, flag = ''):
  749. """!List of elements as strings.
  750. Returns the output from running g.mlist, as a list of qualified
  751. names.
  752. @param type element type (rast, vect, rast3d, region, ...)
  753. @param pattern pattern string
  754. @param mapset mapset name (if not given use search path)
  755. @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or '' (glob pattern)
  756. @return list of elements
  757. """
  758. if type == 'raster' or type == 'cell':
  759. verbose(_('Element type should be "rast" and not "%s"') % element)
  760. type = 'rast'
  761. result = list()
  762. for line in read_command("g.mlist",
  763. quiet = True,
  764. flags = 'm' + flag,
  765. type = type,
  766. pattern = pattern,
  767. mapset = mapset).splitlines():
  768. result.append(line.strip())
  769. return result
  770. def mlist_pairs(type, pattern = None, mapset = None, flag = ''):
  771. """!List of elements as pairs
  772. Returns the output from running g.mlist, as a list of
  773. (name, mapset) pairs
  774. @param type element type (rast, vect, rast3d, region, ...)
  775. @param pattern pattern string
  776. @param mapset mapset name (if not given use search path)
  777. @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or '' (glob pattern)
  778. @return list of elements
  779. """
  780. return [tuple(map.split('@', 1)) for map in mlist_strings(type, pattern, mapset, flag)]
  781. def mlist_grouped(type, pattern = None, check_search_path = True, flag = ''):
  782. """!List of elements grouped by mapsets.
  783. Returns the output from running g.mlist, as a dictionary where the
  784. keys are mapset names and the values are lists of maps in that
  785. mapset. Example:
  786. @code
  787. >>> grass.mlist_grouped('rast', pattern='r*')['PERMANENT']
  788. ['railroads', 'roads', 'rstrct.areas', 'rushmore']
  789. @endcode
  790. @param type element type (rast, vect, rast3d, region, ...)
  791. @param pattern pattern string
  792. @param check_search_path True to add mapsets for the search path with no found elements
  793. @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or '' (glob pattern)
  794. @return directory of mapsets/elements
  795. """
  796. if type == 'raster' or type == 'cell':
  797. verbose(_('Element type should be "rast" and not "%s"') % element)
  798. type = 'rast'
  799. result = {}
  800. if check_search_path:
  801. for mapset in mapsets(search_path = True):
  802. result[mapset] = []
  803. mapset = None
  804. for line in read_command("g.mlist", quiet = True, flags = "m" + flag,
  805. type = type, pattern = pattern).splitlines():
  806. try:
  807. name, mapset = line.split('@')
  808. except ValueError:
  809. warning(_("Invalid element '%s'") % line)
  810. continue
  811. if mapset in result:
  812. result[mapset].append(name)
  813. else:
  814. result[mapset] = [name, ]
  815. return result
  816. # color parsing
  817. named_colors = {
  818. "white": (1.00, 1.00, 1.00),
  819. "black": (0.00, 0.00, 0.00),
  820. "red": (1.00, 0.00, 0.00),
  821. "green": (0.00, 1.00, 0.00),
  822. "blue": (0.00, 0.00, 1.00),
  823. "yellow": (1.00, 1.00, 0.00),
  824. "magenta": (1.00, 0.00, 1.00),
  825. "cyan": (0.00, 1.00, 1.00),
  826. "aqua": (0.00, 0.75, 0.75),
  827. "grey": (0.75, 0.75, 0.75),
  828. "gray": (0.75, 0.75, 0.75),
  829. "orange": (1.00, 0.50, 0.00),
  830. "brown": (0.75, 0.50, 0.25),
  831. "purple": (0.50, 0.00, 1.00),
  832. "violet": (0.50, 0.00, 1.00),
  833. "indigo": (0.00, 0.50, 1.00)}
  834. def parse_color(val, dflt = None):
  835. """!Parses the string "val" as a GRASS colour, which can be either one of
  836. the named colours or an R:G:B tuple e.g. 255:255:255. Returns an
  837. (r,g,b) triple whose components are floating point values between 0
  838. and 1. Example:
  839. \code
  840. >>> grass.parse_color("red")
  841. (1.0, 0.0, 0.0)
  842. >>> grass.parse_color("255:0:0")
  843. (1.0, 0.0, 0.0)
  844. \endcode
  845. @param val color value
  846. @param dflt default color value
  847. @return tuple RGB
  848. """
  849. if val in named_colors:
  850. return named_colors[val]
  851. vals = val.split(':')
  852. if len(vals) == 3:
  853. return tuple(float(v) / 255 for v in vals)
  854. return dflt
  855. # check GRASS_OVERWRITE
  856. def overwrite():
  857. """!Return True if existing files may be overwritten"""
  858. owstr = 'GRASS_OVERWRITE'
  859. return owstr in os.environ and os.environ[owstr] != '0'
  860. # check GRASS_VERBOSE
  861. def verbosity():
  862. """!Return the verbosity level selected by GRASS_VERBOSE"""
  863. vbstr = os.getenv('GRASS_VERBOSE')
  864. if vbstr:
  865. return int(vbstr)
  866. else:
  867. return 2
  868. ## various utilities, not specific to GRASS
  869. # basename inc. extension stripping
  870. def basename(path, ext = None):
  871. """!Remove leading directory components and an optional extension
  872. from the specified path
  873. @param path path
  874. @param ext extension
  875. """
  876. name = os.path.basename(path)
  877. if not ext:
  878. return name
  879. fs = name.rsplit('.', 1)
  880. if len(fs) > 1 and fs[1].lower() == ext:
  881. name = fs[0]
  882. return name
  883. # find a program (replacement for "which")
  884. def find_program(pgm, args = []):
  885. """!Attempt to run a program, with optional arguments.
  886. @param pgm program name
  887. @param args list of arguments
  888. @return False if the attempt failed due to a missing executable
  889. @return True otherwise
  890. """
  891. nuldev = file(os.devnull, 'w+')
  892. try:
  893. ret = call([pgm] + args, stdin = nuldev, stdout = nuldev, stderr = nuldev)
  894. if ret == 0:
  895. found = True
  896. else:
  897. found = False
  898. except:
  899. found = False
  900. nuldev.close()
  901. return found
  902. # try to remove a file, without complaints
  903. def try_remove(path):
  904. """!Attempt to remove a file; no exception is generated if the
  905. attempt fails.
  906. @param path path to file to remove
  907. """
  908. try:
  909. os.remove(path)
  910. except:
  911. pass
  912. # try to remove a directory, without complaints
  913. def try_rmdir(path):
  914. """!Attempt to remove a directory; no exception is generated if the
  915. attempt fails.
  916. @param path path to directory to remove
  917. """
  918. try:
  919. os.rmdir(path)
  920. except:
  921. shutil.rmtree(path, ignore_errors = True)
  922. def float_or_dms(s):
  923. """!Convert DMS to float.
  924. @param s DMS value
  925. @return float value
  926. """
  927. return sum(float(x) / 60 ** n for (n, x) in enumerate(s.split(':')))
  928. # interface to g.mapsets
  929. def mapsets(search_path = False):
  930. """!List available mapsets
  931. @param searchPatch True to list mapsets only in search path
  932. @return list of mapsets
  933. """
  934. if search_path:
  935. flags = 'p'
  936. else:
  937. flags = 'l'
  938. mapsets = read_command('g.mapsets',
  939. flags = flags,
  940. fs = 'newline',
  941. quiet = True)
  942. if not mapsets:
  943. fatal(_("Unable to list mapsets"))
  944. return mapsets.splitlines()
  945. # interface to `g.proj -c`
  946. def create_location(dbase, location,
  947. epsg = None, proj4 = None, filename = None, wkt = None,
  948. datum = None, desc = None):
  949. """!Create new location
  950. Raise ScriptError on error.
  951. @param dbase path to GRASS database
  952. @param location location name to create
  953. @param epgs if given create new location based on EPSG code
  954. @param proj4 if given create new location based on Proj4 definition
  955. @param filename if given create new location based on georeferenced file
  956. @param wkt if given create new location based on WKT definition (path to PRJ file)
  957. @param datum datum transformation parameters (used for epsg and proj4)
  958. @param desc description of the location (creates MYNAME file)
  959. """
  960. gisdbase = None
  961. if epsg or proj4 or filename or wkt:
  962. gisdbase = gisenv()['GISDBASE']
  963. run_command('g.gisenv',
  964. set = 'GISDBASE=%s' % dbase)
  965. if not os.path.exists(dbase):
  966. os.mkdir(dbase)
  967. kwargs = dict()
  968. if datum:
  969. kwargs['datum'] = datum
  970. if epsg:
  971. ps = pipe_command('g.proj',
  972. quiet = True,
  973. epsg = epsg,
  974. location = location,
  975. stderr = PIPE,
  976. **kwargs)
  977. elif proj4:
  978. ps = pipe_command('g.proj',
  979. quiet = True,
  980. proj4 = proj4,
  981. location = location,
  982. stderr = PIPE,
  983. **kwargs)
  984. elif filename:
  985. ps = pipe_command('g.proj',
  986. quiet = True,
  987. georef = filename,
  988. location = location,
  989. stderr = PIPE)
  990. elif wkt:
  991. ps = pipe_command('g.proj',
  992. quiet = True,
  993. wkt = wkt,
  994. location = location,
  995. stderr = PIPE)
  996. else:
  997. _create_location_xy(dbase, location)
  998. if epsg or proj4 or filename or wkt:
  999. error = ps.communicate()[1]
  1000. run_command('g.gisenv',
  1001. set = 'GISDBASE=%s' % gisdbase)
  1002. if ps.returncode != 0 and error:
  1003. raise ScriptError(repr(error))
  1004. try:
  1005. fd = codecs.open(os.path.join(dbase, location,
  1006. 'PERMANENT', 'MYNAME'),
  1007. encoding = 'utf-8', mode = 'w')
  1008. if desc:
  1009. fd.write(desc + os.linesep)
  1010. else:
  1011. fd.write(os.linesep)
  1012. fd.close()
  1013. except OSError, e:
  1014. raise ScriptError(repr(e))
  1015. def _create_location_xy(database, location):
  1016. """!Create unprojected location
  1017. Raise ScriptError on error.
  1018. @param database GRASS database where to create new location
  1019. @param location location name
  1020. """
  1021. cur_dir = os.getcwd()
  1022. try:
  1023. os.chdir(database)
  1024. os.mkdir(location)
  1025. os.mkdir(os.path.join(location, 'PERMANENT'))
  1026. # create DEFAULT_WIND and WIND files
  1027. regioninfo = ['proj: 0',
  1028. 'zone: 0',
  1029. 'north: 1',
  1030. 'south: 0',
  1031. 'east: 1',
  1032. 'west: 0',
  1033. 'cols: 1',
  1034. 'rows: 1',
  1035. 'e-w resol: 1',
  1036. 'n-s resol: 1',
  1037. 'top: 1',
  1038. 'bottom: 0',
  1039. 'cols3: 1',
  1040. 'rows3: 1',
  1041. 'depths: 1',
  1042. 'e-w resol3: 1',
  1043. 'n-s resol3: 1',
  1044. 't-b resol: 1']
  1045. defwind = open(os.path.join(location,
  1046. "PERMANENT", "DEFAULT_WIND"), 'w')
  1047. for param in regioninfo:
  1048. defwind.write(param + '%s' % os.linesep)
  1049. defwind.close()
  1050. shutil.copy(os.path.join(location, "PERMANENT", "DEFAULT_WIND"),
  1051. os.path.join(location, "PERMANENT", "WIND"))
  1052. os.chdir(cur_dir)
  1053. except OSError, e:
  1054. raise ScriptError(repr(e))
  1055. # interface to g.version
  1056. def version():
  1057. """!Get GRASS version as dictionary
  1058. @code
  1059. print version()
  1060. {'date': '2011', 'libgis_date': '2011-08-13 01:14:30 +0200 (Sat, 13 Aug 2011)',
  1061. 'version': '7.0.svn', 'libgis_revision': '47604', 'revision': '47963'}
  1062. @endcode
  1063. """
  1064. data = parse_command('g.version',
  1065. flags = 'rg')
  1066. for k, v in data.iteritems():
  1067. data[k.strip()] = v.replace('"', '').strip()
  1068. return data
  1069. # get debug_level
  1070. if find_program('g.gisenv', ['--help']):
  1071. debug_level = int(gisenv().get('DEBUG', 0))