core.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  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 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. print dict_a
  545. print dict_b
  546. missing_keys = 0
  547. # We compare matching keys
  548. for key in dict_a.keys():
  549. if dict_b.has_key(key):
  550. # Floating point values must be handled separately
  551. if isinstance(dict_a[key], float) and isinstance(dict_b[key], float):
  552. if abs(dict_a[key] - dict_b[key]) > precision:
  553. return False
  554. elif isinstance(dict_a[key], float) or isinstance(dict_b[key], float):
  555. warning(_("Mixing value types. Will try to compare after "
  556. "integer conversion"))
  557. return int(dict_a[key]) == int(dict_b[key])
  558. elif key == "+towgs84":
  559. # We compare the sum of the entries
  560. if abs(sum(dict_a[key]) - sum(dict_b[key])) > precision:
  561. return False
  562. else:
  563. if dict_a[key] != dict_b[key]:
  564. return False
  565. else:
  566. missing_keys += 1
  567. if missing_keys == len(dict_a):
  568. return False
  569. if missing_keys > 0:
  570. warning(_("Several keys (%i out of %i) are missing "
  571. "in the target file")%(missing_keys, len(dict_a)))
  572. return True
  573. # interface to g.gisenv
  574. def gisenv():
  575. """!Returns the output from running g.gisenv (with no arguments), as a
  576. dictionary. Example:
  577. \code
  578. >>> env = grass.gisenv()
  579. >>> print env['GISDBASE']
  580. /opt/grass-data
  581. \endcode
  582. @return list of GRASS variables
  583. """
  584. s = read_command("g.gisenv", flags='n')
  585. return parse_key_val(s)
  586. # interface to g.region
  587. def locn_is_latlong():
  588. """!Tests if location is lat/long. Value is obtained
  589. by checking the "g.region -p" projection code.
  590. @return True for a lat/long region, False otherwise
  591. """
  592. s = read_command("g.region", flags='p')
  593. kv = parse_key_val(s, ':')
  594. if kv['projection'].split(' ')[1] == '3':
  595. return True
  596. else:
  597. return False
  598. def region(region3d = False, complete = False):
  599. """!Returns the output from running "g.region -g", as a
  600. dictionary. Example:
  601. \param region3d True to get 3D region
  602. \code
  603. >>> region = grass.region()
  604. >>> [region[key] for key in "nsew"]
  605. [228500.0, 215000.0, 645000.0, 630000.0]
  606. >>> (region['nsres'], region['ewres'])
  607. (10.0, 10.0)
  608. \endcode
  609. @return dictionary of region values
  610. """
  611. flgs = 'g'
  612. if region3d:
  613. flgs += '3'
  614. if complete:
  615. flgs += 'cep'
  616. s = read_command("g.region", flags = flgs)
  617. reg = parse_key_val(s, val_type = float)
  618. for k in ['rows', 'cols', 'cells',
  619. 'rows3', 'cols3', 'cells3', 'depths']:
  620. if k not in reg:
  621. continue
  622. reg[k] = int(reg[k])
  623. return reg
  624. def region_env(region3d = False,
  625. **kwargs):
  626. """!Returns region settings as a string which can used as
  627. GRASS_REGION environmental variable.
  628. If no 'kwargs' are given then the current region is used. Note
  629. that this function doesn't modify the current region!
  630. See also use_temp_region() for alternative method how to define
  631. temporary region used for raster-based computation.
  632. \param region3d True to get 3D region
  633. \param kwargs g.region's parameters like 'rast', 'vect' or 'region'
  634. \code
  635. os.environ['GRASS_REGION'] = grass.region_env(region = 'detail')
  636. grass.mapcalc('map = 1', overwrite = True)
  637. os.environ.pop('GRASS_REGION')
  638. \endcode
  639. @return string with region values
  640. @return empty string on error
  641. """
  642. # read proj/zone from WIND file
  643. env = gisenv()
  644. windfile = os.path.join (env['GISDBASE'], env['LOCATION_NAME'],
  645. env['MAPSET'], "WIND")
  646. fd = open(windfile, "r")
  647. grass_region = ''
  648. for line in fd.readlines():
  649. key, value = map(lambda x: x.strip(), line.split(":", 1))
  650. if kwargs and key not in ('proj', 'zone'):
  651. continue
  652. if not kwargs and not region3d and \
  653. key in ('top', 'bottom', 'cols3', 'rows3',
  654. 'depths', 'e-w resol3', 'n-s resol3', 't-b resol'):
  655. continue
  656. grass_region += '%s: %s;' % (key, value)
  657. if not kwargs: # return current region
  658. return grass_region
  659. # read other values from `g.region -g`
  660. flgs = 'ug'
  661. if region3d:
  662. flgs += '3'
  663. s = read_command('g.region', flags = flgs, **kwargs)
  664. if not s:
  665. return ''
  666. reg = parse_key_val(s)
  667. kwdata = [('north', 'n'),
  668. ('south', 's'),
  669. ('east', 'e'),
  670. ('west', 'w'),
  671. ('cols', 'cols'),
  672. ('rows', 'rows'),
  673. ('e-w resol', 'ewres'),
  674. ('n-s resol', 'nsres')]
  675. if region3d:
  676. kwdata += [('top', 't'),
  677. ('bottom', 'b'),
  678. ('cols3', 'cols3'),
  679. ('rows3', 'rows3'),
  680. ('depths', 'depths'),
  681. ('e-w resol3', 'ewres3'),
  682. ('n-s resol3', 'nsres3'),
  683. ('t-b resol', 'tbres')]
  684. for wkey, rkey in kwdata:
  685. grass_region += '%s: %s;' % (wkey, reg[rkey])
  686. return grass_region
  687. def use_temp_region():
  688. """!Copies the current region to a temporary region with "g.region save=",
  689. then sets WIND_OVERRIDE to refer to that region. Installs an atexit
  690. handler to delete the temporary region upon termination.
  691. """
  692. name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
  693. run_command("g.region", save = name, overwrite = True)
  694. os.environ['WIND_OVERRIDE'] = name
  695. atexit.register(del_temp_region)
  696. def del_temp_region():
  697. """!Unsets WIND_OVERRIDE and removes any region named by it."""
  698. try:
  699. name = os.environ.pop('WIND_OVERRIDE')
  700. run_command("g.remove", quiet = True, region = name)
  701. except:
  702. pass
  703. # interface to g.findfile
  704. def find_file(name, element = 'cell', mapset = None):
  705. """!Returns the output from running g.findfile as a
  706. dictionary. Example:
  707. \code
  708. >>> result = grass.find_file('fields', element = 'vector')
  709. >>> print result['fullname']
  710. fields@PERMANENT
  711. >>> print result['file']
  712. /opt/grass-data/spearfish60/PERMANENT/vector/fields
  713. \endcode
  714. @param name file name
  715. @param element element type (default 'cell')
  716. @param mapset mapset name (default all mapsets in search path)
  717. @return parsed output of g.findfile
  718. """
  719. if element == 'raster' or element == 'rast':
  720. verbose(_('Element type should be "cell" and not "%s"') % element)
  721. element = 'cell'
  722. s = read_command("g.findfile", flags='n', element = element, file = name, mapset = mapset)
  723. return parse_key_val(s)
  724. # interface to g.list
  725. def list_grouped(type, check_search_path = True):
  726. """!List elements grouped by mapsets.
  727. Returns the output from running g.list, as a dictionary where the
  728. keys are mapset names and the values are lists of maps in that
  729. mapset. Example:
  730. @code
  731. >>> grass.list_grouped('rast')['PERMANENT']
  732. ['aspect', 'erosion1', 'quads', 'soils', 'strm.dist', ...
  733. @endcode
  734. @param type element type (rast, vect, rast3d, region, ...)
  735. @param check_search_path True to add mapsets for the search path with no found elements
  736. @return directory of mapsets/elements
  737. """
  738. if type == 'raster' or type == 'cell':
  739. verbose(_('Element type should be "rast" and not "%s"') % element)
  740. type = 'rast'
  741. dashes_re = re.compile("^----+$")
  742. mapset_re = re.compile("<(.*)>")
  743. result = {}
  744. if check_search_path:
  745. for mapset in mapsets(search_path = True):
  746. result[mapset] = []
  747. mapset = None
  748. for line in read_command("g.list", type = type).splitlines():
  749. if line == "":
  750. continue
  751. if dashes_re.match(line):
  752. continue
  753. m = mapset_re.search(line)
  754. if m:
  755. mapset = m.group(1)
  756. if mapset not in result.keys():
  757. result[mapset] = []
  758. continue
  759. if mapset:
  760. result[mapset].extend(line.split())
  761. return result
  762. def _concat(xs):
  763. result = []
  764. for x in xs:
  765. result.extend(x)
  766. return result
  767. def list_pairs(type):
  768. """!List of elements as tuples.
  769. Returns the output from running g.list, as a list of (map, mapset)
  770. pairs. Example:
  771. @code
  772. >>> grass.list_pairs('rast')
  773. [('aspect', 'PERMANENT'), ('erosion1', 'PERMANENT'), ('quads', 'PERMANENT'), ...
  774. @endcode
  775. @param type element type (rast, vect, rast3d, region, ...)
  776. @return list of tuples (map, mapset)
  777. """
  778. return _concat([[(map, mapset) for map in maps]
  779. for mapset, maps in list_grouped(type).iteritems()])
  780. def list_strings(type):
  781. """!List of elements as strings.
  782. Returns the output from running g.list, as a list of qualified
  783. names. Example:
  784. @code
  785. >>> grass.list_strings('rast')
  786. ['aspect@PERMANENT', 'erosion1@PERMANENT', 'quads@PERMANENT', 'soils@PERMANENT', ...
  787. @endcode
  788. @param type element type
  789. @return list of strings ('map@@mapset')
  790. """
  791. return ["%s@%s" % pair for pair in list_pairs(type)]
  792. # interface to g.mlist
  793. def mlist_strings(type, pattern = None, mapset = None, flag = ''):
  794. """!List of elements as strings.
  795. Returns the output from running g.mlist, as a list of qualified
  796. names.
  797. @param type element type (rast, vect, rast3d, region, ...)
  798. @param pattern pattern string
  799. @param mapset mapset name (if not given use search path)
  800. @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or '' (glob pattern)
  801. @return list of elements
  802. """
  803. if type == 'raster' or type == 'cell':
  804. verbose(_('Element type should be "rast" and not "%s"') % element)
  805. type = 'rast'
  806. result = list()
  807. for line in read_command("g.mlist",
  808. quiet = True,
  809. flags = 'm' + flag,
  810. type = type,
  811. pattern = pattern,
  812. mapset = mapset).splitlines():
  813. result.append(line.strip())
  814. return result
  815. def mlist_pairs(type, pattern = None, mapset = None, flag = ''):
  816. """!List of elements as pairs
  817. Returns the output from running g.mlist, as a list of
  818. (name, mapset) pairs
  819. @param type element type (rast, vect, rast3d, region, ...)
  820. @param pattern pattern string
  821. @param mapset mapset name (if not given use search path)
  822. @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or '' (glob pattern)
  823. @return list of elements
  824. """
  825. return [tuple(map.split('@', 1)) for map in mlist_strings(type, pattern, mapset, flag)]
  826. def mlist_grouped(type, pattern = None, check_search_path = True, flag = ''):
  827. """!List of elements grouped by mapsets.
  828. Returns the output from running g.mlist, as a dictionary where the
  829. keys are mapset names and the values are lists of maps in that
  830. mapset. Example:
  831. @code
  832. >>> grass.mlist_grouped('rast', pattern='r*')['PERMANENT']
  833. ['railroads', 'roads', 'rstrct.areas', 'rushmore']
  834. @endcode
  835. @param type element type (rast, vect, rast3d, region, ...)
  836. @param pattern pattern string
  837. @param check_search_path True to add mapsets for the search path with no found elements
  838. @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or '' (glob pattern)
  839. @return directory of mapsets/elements
  840. """
  841. if type == 'raster' or type == 'cell':
  842. verbose(_('Element type should be "rast" and not "%s"') % element)
  843. type = 'rast'
  844. result = {}
  845. if check_search_path:
  846. for mapset in mapsets(search_path = True):
  847. result[mapset] = []
  848. mapset = None
  849. for line in read_command("g.mlist", quiet = True, flags = "m" + flag,
  850. type = type, pattern = pattern).splitlines():
  851. try:
  852. name, mapset = line.split('@')
  853. except ValueError:
  854. warning(_("Invalid element '%s'") % line)
  855. continue
  856. if mapset in result:
  857. result[mapset].append(name)
  858. else:
  859. result[mapset] = [name, ]
  860. return result
  861. # color parsing
  862. named_colors = {
  863. "white": (1.00, 1.00, 1.00),
  864. "black": (0.00, 0.00, 0.00),
  865. "red": (1.00, 0.00, 0.00),
  866. "green": (0.00, 1.00, 0.00),
  867. "blue": (0.00, 0.00, 1.00),
  868. "yellow": (1.00, 1.00, 0.00),
  869. "magenta": (1.00, 0.00, 1.00),
  870. "cyan": (0.00, 1.00, 1.00),
  871. "aqua": (0.00, 0.75, 0.75),
  872. "grey": (0.75, 0.75, 0.75),
  873. "gray": (0.75, 0.75, 0.75),
  874. "orange": (1.00, 0.50, 0.00),
  875. "brown": (0.75, 0.50, 0.25),
  876. "purple": (0.50, 0.00, 1.00),
  877. "violet": (0.50, 0.00, 1.00),
  878. "indigo": (0.00, 0.50, 1.00)}
  879. def parse_color(val, dflt = None):
  880. """!Parses the string "val" as a GRASS colour, which can be either one of
  881. the named colours or an R:G:B tuple e.g. 255:255:255. Returns an
  882. (r,g,b) triple whose components are floating point values between 0
  883. and 1. Example:
  884. \code
  885. >>> grass.parse_color("red")
  886. (1.0, 0.0, 0.0)
  887. >>> grass.parse_color("255:0:0")
  888. (1.0, 0.0, 0.0)
  889. \endcode
  890. @param val color value
  891. @param dflt default color value
  892. @return tuple RGB
  893. """
  894. if val in named_colors:
  895. return named_colors[val]
  896. vals = val.split(':')
  897. if len(vals) == 3:
  898. return tuple(float(v) / 255 for v in vals)
  899. return dflt
  900. # check GRASS_OVERWRITE
  901. def overwrite():
  902. """!Return True if existing files may be overwritten"""
  903. owstr = 'GRASS_OVERWRITE'
  904. return owstr in os.environ and os.environ[owstr] != '0'
  905. # check GRASS_VERBOSE
  906. def verbosity():
  907. """!Return the verbosity level selected by GRASS_VERBOSE"""
  908. vbstr = os.getenv('GRASS_VERBOSE')
  909. if vbstr:
  910. return int(vbstr)
  911. else:
  912. return 2
  913. ## various utilities, not specific to GRASS
  914. # basename inc. extension stripping
  915. def basename(path, ext = None):
  916. """!Remove leading directory components and an optional extension
  917. from the specified path
  918. @param path path
  919. @param ext extension
  920. """
  921. name = os.path.basename(path)
  922. if not ext:
  923. return name
  924. fs = name.rsplit('.', 1)
  925. if len(fs) > 1 and fs[1].lower() == ext:
  926. name = fs[0]
  927. return name
  928. # find a program (replacement for "which")
  929. def find_program(pgm, args = []):
  930. """!Attempt to run a program, with optional arguments.
  931. @param pgm program name
  932. @param args list of arguments
  933. @return False if the attempt failed due to a missing executable
  934. @return True otherwise
  935. """
  936. nuldev = file(os.devnull, 'w+')
  937. try:
  938. ret = call([pgm] + args, stdin = nuldev, stdout = nuldev, stderr = nuldev)
  939. if ret == 0:
  940. found = True
  941. else:
  942. found = False
  943. except:
  944. found = False
  945. nuldev.close()
  946. return found
  947. # try to remove a file, without complaints
  948. def try_remove(path):
  949. """!Attempt to remove a file; no exception is generated if the
  950. attempt fails.
  951. @param path path to file to remove
  952. """
  953. try:
  954. os.remove(path)
  955. except:
  956. pass
  957. # try to remove a directory, without complaints
  958. def try_rmdir(path):
  959. """!Attempt to remove a directory; no exception is generated if the
  960. attempt fails.
  961. @param path path to directory to remove
  962. """
  963. try:
  964. os.rmdir(path)
  965. except:
  966. shutil.rmtree(path, ignore_errors = True)
  967. def float_or_dms(s):
  968. """!Convert DMS to float.
  969. @param s DMS value
  970. @return float value
  971. """
  972. return sum(float(x) / 60 ** n for (n, x) in enumerate(s.split(':')))
  973. # interface to g.mapsets
  974. def mapsets(search_path = False):
  975. """!List available mapsets
  976. @param search_path True to list mapsets only in search path
  977. @return list of mapsets
  978. """
  979. if search_path:
  980. flags = 'p'
  981. else:
  982. flags = 'l'
  983. mapsets = read_command('g.mapsets',
  984. flags = flags,
  985. sep = 'newline',
  986. quiet = True)
  987. if not mapsets:
  988. fatal(_("Unable to list mapsets"))
  989. return mapsets.splitlines()
  990. # interface to `g.proj -c`
  991. def create_location(dbase, location,
  992. epsg = None, proj4 = None, filename = None, wkt = None,
  993. datum = None, datum_trans = None, desc = None):
  994. """!Create new location
  995. Raise ScriptError on error.
  996. @param dbase path to GRASS database
  997. @param location location name to create
  998. @param epsg if given create new location based on EPSG code
  999. @param proj4 if given create new location based on Proj4 definition
  1000. @param filename if given create new location based on georeferenced file
  1001. @param wkt if given create new location based on WKT definition (path to PRJ file)
  1002. @param datum GRASS format datum code
  1003. @param datum_trans datum transformation parameters (used for epsg and proj4)
  1004. @param desc description of the location (creates MYNAME file)
  1005. """
  1006. gisdbase = None
  1007. if epsg or proj4 or filename or wkt:
  1008. gisdbase = gisenv()['GISDBASE']
  1009. run_command('g.gisenv',
  1010. set = 'GISDBASE=%s' % dbase)
  1011. if not os.path.exists(dbase):
  1012. os.mkdir(dbase)
  1013. kwargs = dict()
  1014. if datum:
  1015. kwargs['datum'] = datum
  1016. if datum_trans:
  1017. kwargs['datum_trans'] = datum_trans
  1018. if epsg:
  1019. ps = pipe_command('g.proj',
  1020. quiet = True,
  1021. epsg = epsg,
  1022. location = location,
  1023. stderr = PIPE,
  1024. **kwargs)
  1025. elif proj4:
  1026. ps = pipe_command('g.proj',
  1027. quiet = True,
  1028. proj4 = proj4,
  1029. location = location,
  1030. stderr = PIPE,
  1031. **kwargs)
  1032. elif filename:
  1033. ps = pipe_command('g.proj',
  1034. quiet = True,
  1035. georef = filename,
  1036. location = location,
  1037. stderr = PIPE)
  1038. elif wkt:
  1039. ps = pipe_command('g.proj',
  1040. quiet = True,
  1041. wkt = wkt,
  1042. location = location,
  1043. stderr = PIPE)
  1044. else:
  1045. _create_location_xy(dbase, location)
  1046. if epsg or proj4 or filename or wkt:
  1047. error = ps.communicate()[1]
  1048. run_command('g.gisenv',
  1049. set = 'GISDBASE=%s' % gisdbase)
  1050. if ps.returncode != 0 and error:
  1051. raise ScriptError(repr(error))
  1052. try:
  1053. fd = codecs.open(os.path.join(dbase, location,
  1054. 'PERMANENT', 'MYNAME'),
  1055. encoding = 'utf-8', mode = 'w')
  1056. if desc:
  1057. fd.write(desc + os.linesep)
  1058. else:
  1059. fd.write(os.linesep)
  1060. fd.close()
  1061. except OSError, e:
  1062. raise ScriptError(repr(e))
  1063. def _create_location_xy(database, location):
  1064. """!Create unprojected location
  1065. Raise ScriptError on error.
  1066. @param database GRASS database where to create new location
  1067. @param location location name
  1068. """
  1069. cur_dir = os.getcwd()
  1070. try:
  1071. os.chdir(database)
  1072. os.mkdir(location)
  1073. os.mkdir(os.path.join(location, 'PERMANENT'))
  1074. # create DEFAULT_WIND and WIND files
  1075. regioninfo = ['proj: 0',
  1076. 'zone: 0',
  1077. 'north: 1',
  1078. 'south: 0',
  1079. 'east: 1',
  1080. 'west: 0',
  1081. 'cols: 1',
  1082. 'rows: 1',
  1083. 'e-w resol: 1',
  1084. 'n-s resol: 1',
  1085. 'top: 1',
  1086. 'bottom: 0',
  1087. 'cols3: 1',
  1088. 'rows3: 1',
  1089. 'depths: 1',
  1090. 'e-w resol3: 1',
  1091. 'n-s resol3: 1',
  1092. 't-b resol: 1']
  1093. defwind = open(os.path.join(location,
  1094. "PERMANENT", "DEFAULT_WIND"), 'w')
  1095. for param in regioninfo:
  1096. defwind.write(param + '%s' % os.linesep)
  1097. defwind.close()
  1098. shutil.copy(os.path.join(location, "PERMANENT", "DEFAULT_WIND"),
  1099. os.path.join(location, "PERMANENT", "WIND"))
  1100. os.chdir(cur_dir)
  1101. except OSError, e:
  1102. raise ScriptError(repr(e))
  1103. # interface to g.version
  1104. def version():
  1105. """!Get GRASS version as dictionary
  1106. @code
  1107. print version()
  1108. {'proj4': '4.8.0', 'geos': '3.3.5', 'libgis_revision': '52468',
  1109. 'libgis_date': '2012-07-27 22:53:30 +0200 (Fri, 27 Jul 2012)',
  1110. 'version': '7.0.svn', 'date': '2012', 'gdal': '2.0dev', 'revision': '53670'}
  1111. @endcode
  1112. """
  1113. data = parse_command('g.version',
  1114. flags = 'rge')
  1115. for k, v in data.iteritems():
  1116. data[k.strip()] = v.replace('"', '').strip()
  1117. return data
  1118. # get debug_level
  1119. _debug_level = None
  1120. def debug_level():
  1121. global _debug_level
  1122. if _debug_level is not None:
  1123. return _debug_level
  1124. _debug_level = 0
  1125. if find_program('g.gisenv', ['--help']):
  1126. _debug_level = int(gisenv().get('DEBUG', 0))