core.py 40 KB

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