core.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422
  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 two files
  523. This method will print a warning in case keys that are present in the first file
  524. are not present in the second one.
  525. The comparison method tries to convert the values into there native format (float, int or string)
  526. to allow correct comparison.
  527. An example key-value text file may have this content:
  528. \code
  529. a: Hello
  530. b: 1.0
  531. c: 1,2,3,4,5
  532. d : hello,8,0.1
  533. \endcode
  534. @param filename_a name of the first key-value text file
  535. @param filenmae_b name of the second key-value text file
  536. @param sep character that separates the keys and values, default is ":"
  537. @param val_sep character that separates the values of a single key, default is ","
  538. @param precision precision with which the floating point values are compares
  539. @return True if full or almost identical, False if different
  540. """
  541. dict_a = _text_to_key_value_dict(filename_a, sep)
  542. dict_b = _text_to_key_value_dict(filename_b, sep)
  543. missing_keys = 0
  544. # We compare matching keys
  545. for key in dict_a.keys():
  546. if dict_b.has_key(key):
  547. # Floating point values must be handled separately
  548. if isinstance(dict_a[key], float) and isinstance(dict_b[key], float):
  549. if abs(dict_a[key] - dict_b[key]) > precision:
  550. return False
  551. elif isinstance(dict_a[key], float) or isinstance(dict_b[key], float):
  552. warning(_("Mixing value types. Will try to compare after "
  553. "integer conversion"))
  554. return int(dict_a[key]) == int(dict_b[key])
  555. elif key == "+towgs84":
  556. # We compare the sum of the entries
  557. if abs(sum(dict_a[key]) - sum(dict_b[key])) > precision:
  558. return False
  559. else:
  560. if dict_a[key] != dict_b[key]:
  561. return False
  562. else:
  563. missing_keys += 1
  564. if missing_keys == len(dict_a):
  565. return False
  566. if missing_keys > 0:
  567. warning(_("Several keys (%i out of %i) are missing "
  568. "in the target file")%(missing_keys, len(dict_a)))
  569. return True
  570. # interface to g.gisenv
  571. def gisenv():
  572. """!Returns the output from running g.gisenv (with no arguments), as a
  573. dictionary. Example:
  574. \code
  575. >>> env = grass.gisenv()
  576. >>> print env['GISDBASE']
  577. /opt/grass-data
  578. \endcode
  579. @return list of GRASS variables
  580. """
  581. s = read_command("g.gisenv", flags='n')
  582. return parse_key_val(s)
  583. # interface to g.region
  584. def locn_is_latlong():
  585. """!Tests if location is lat/long. Value is obtained
  586. by checking the "g.region -p" projection code.
  587. @return True for a lat/long region, False otherwise
  588. """
  589. s = read_command("g.region", flags='p')
  590. kv = parse_key_val(s, ':')
  591. if kv['projection'].split(' ')[1] == '3':
  592. return True
  593. else:
  594. return False
  595. def region(region3d = False, complete = False):
  596. """!Returns the output from running "g.region -g", as a
  597. dictionary. Example:
  598. \param region3d True to get 3D region
  599. \code
  600. >>> region = grass.region()
  601. >>> [region[key] for key in "nsew"]
  602. [228500.0, 215000.0, 645000.0, 630000.0]
  603. >>> (region['nsres'], region['ewres'])
  604. (10.0, 10.0)
  605. \endcode
  606. @return dictionary of region values
  607. """
  608. flgs = 'g'
  609. if region3d:
  610. flgs += '3'
  611. if complete:
  612. flgs += 'cep'
  613. s = read_command("g.region", flags = flgs)
  614. reg = parse_key_val(s, val_type = float)
  615. for k in ['rows', 'cols', 'cells',
  616. 'rows3', 'cols3', 'cells3', 'depths']:
  617. if k not in reg:
  618. continue
  619. reg[k] = int(reg[k])
  620. return reg
  621. def region_env(region3d = False,
  622. **kwargs):
  623. """!Returns region settings as a string which can used as
  624. GRASS_REGION environmental variable.
  625. If no 'kwargs' are given then the current region is used. Note
  626. that this function doesn't modify the current region!
  627. See also use_temp_region() for alternative method how to define
  628. temporary region used for raster-based computation.
  629. \param region3d True to get 3D region
  630. \param kwargs g.region's parameters like 'rast', 'vect' or 'region'
  631. \code
  632. os.environ['GRASS_REGION'] = grass.region_env(region = 'detail')
  633. grass.mapcalc('map = 1', overwrite = True)
  634. os.environ.pop('GRASS_REGION')
  635. \endcode
  636. @return string with region values
  637. @return empty string on error
  638. """
  639. # read proj/zone from WIND file
  640. env = gisenv()
  641. windfile = os.path.join (env['GISDBASE'], env['LOCATION_NAME'],
  642. env['MAPSET'], "WIND")
  643. fd = open(windfile, "r")
  644. grass_region = ''
  645. for line in fd.readlines():
  646. key, value = map(lambda x: x.strip(), line.split(":", 1))
  647. if kwargs and key not in ('proj', 'zone'):
  648. continue
  649. if not kwargs and not region3d and \
  650. key in ('top', 'bottom', 'cols3', 'rows3',
  651. 'depths', 'e-w resol3', 'n-s resol3', 't-b resol'):
  652. continue
  653. grass_region += '%s: %s;' % (key, value)
  654. if not kwargs: # return current region
  655. return grass_region
  656. # read other values from `g.region -g`
  657. flgs = 'ug'
  658. if region3d:
  659. flgs += '3'
  660. s = read_command('g.region', flags = flgs, **kwargs)
  661. if not s:
  662. return ''
  663. reg = parse_key_val(s)
  664. kwdata = [('north', 'n'),
  665. ('south', 's'),
  666. ('east', 'e'),
  667. ('west', 'w'),
  668. ('cols', 'cols'),
  669. ('rows', 'rows'),
  670. ('e-w resol', 'ewres'),
  671. ('n-s resol', 'nsres')]
  672. if region3d:
  673. kwdata += [('top', 't'),
  674. ('bottom', 'b'),
  675. ('cols3', 'cols3'),
  676. ('rows3', 'rows3'),
  677. ('depths', 'depths'),
  678. ('e-w resol3', 'ewres3'),
  679. ('n-s resol3', 'nsres3'),
  680. ('t-b resol', 'tbres')]
  681. for wkey, rkey in kwdata:
  682. grass_region += '%s: %s;' % (wkey, reg[rkey])
  683. return grass_region
  684. def use_temp_region():
  685. """!Copies the current region to a temporary region with "g.region save=",
  686. then sets WIND_OVERRIDE to refer to that region. Installs an atexit
  687. handler to delete the temporary region upon termination.
  688. """
  689. name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
  690. run_command("g.region", save = name, overwrite = True)
  691. os.environ['WIND_OVERRIDE'] = name
  692. atexit.register(del_temp_region)
  693. def del_temp_region():
  694. """!Unsets WIND_OVERRIDE and removes any region named by it."""
  695. try:
  696. name = os.environ.pop('WIND_OVERRIDE')
  697. run_command("g.remove", quiet = True, region = name)
  698. except:
  699. pass
  700. # interface to g.findfile
  701. def find_file(name, element = 'cell', mapset = None):
  702. """!Returns the output from running g.findfile as a
  703. dictionary. Example:
  704. \code
  705. >>> result = grass.find_file('fields', element = 'vector')
  706. >>> print result['fullname']
  707. fields@PERMANENT
  708. >>> print result['file']
  709. /opt/grass-data/spearfish60/PERMANENT/vector/fields
  710. \endcode
  711. @param name file name
  712. @param element element type (default 'cell')
  713. @param mapset mapset name (default all mapsets in search path)
  714. @return parsed output of g.findfile
  715. """
  716. if element == 'raster' or element == 'rast':
  717. verbose(_('Element type should be "cell" and not "%s"') % element)
  718. element = 'cell'
  719. s = read_command("g.findfile", flags='n', element = element, file = name, mapset = mapset)
  720. return parse_key_val(s)
  721. # interface to g.list
  722. def list_grouped(type, check_search_path = True):
  723. """!List elements grouped by mapsets.
  724. Returns the output from running g.list, as a dictionary where the
  725. keys are mapset names and the values are lists of maps in that
  726. mapset. Example:
  727. @code
  728. >>> grass.list_grouped('rast')['PERMANENT']
  729. ['aspect', 'erosion1', 'quads', 'soils', 'strm.dist', ...
  730. @endcode
  731. @param type element type (rast, vect, rast3d, region, ...)
  732. @param check_search_path True to add mapsets for the search path with no found elements
  733. @return directory of mapsets/elements
  734. """
  735. if type == 'raster' or type == 'cell':
  736. verbose(_('Element type should be "rast" and not "%s"') % type)
  737. type = 'rast'
  738. dashes_re = re.compile("^----+$")
  739. mapset_re = re.compile("<(.*)>")
  740. result = {}
  741. if check_search_path:
  742. for mapset in mapsets(search_path = True):
  743. result[mapset] = []
  744. mapset = None
  745. for line in read_command("g.list", type = type).splitlines():
  746. if line == "":
  747. continue
  748. if dashes_re.match(line):
  749. continue
  750. m = mapset_re.search(line)
  751. if m:
  752. mapset = m.group(1)
  753. if mapset not in result.keys():
  754. result[mapset] = []
  755. continue
  756. if mapset:
  757. result[mapset].extend(line.split())
  758. return result
  759. def _concat(xs):
  760. result = []
  761. for x in xs:
  762. result.extend(x)
  763. return result
  764. def list_pairs(type):
  765. """!List of elements as tuples.
  766. Returns the output from running g.list, as a list of (map, mapset)
  767. pairs. Example:
  768. @code
  769. >>> grass.list_pairs('rast')
  770. [('aspect', 'PERMANENT'), ('erosion1', 'PERMANENT'), ('quads', 'PERMANENT'), ...
  771. @endcode
  772. @param type element type (rast, vect, rast3d, region, ...)
  773. @return list of tuples (map, mapset)
  774. """
  775. return _concat([[(map, mapset) for map in maps]
  776. for mapset, maps in list_grouped(type).iteritems()])
  777. def list_strings(type):
  778. """!List of elements as strings.
  779. Returns the output from running g.list, as a list of qualified
  780. names. Example:
  781. @code
  782. >>> grass.list_strings('rast')
  783. ['aspect@PERMANENT', 'erosion1@PERMANENT', 'quads@PERMANENT', 'soils@PERMANENT', ...
  784. @endcode
  785. @param type element type
  786. @return list of strings ('map@@mapset')
  787. """
  788. return ["%s@%s" % pair for pair in list_pairs(type)]
  789. # interface to g.mlist
  790. def mlist_strings(type, pattern = None, mapset = None, flag = ''):
  791. """!List of elements as strings.
  792. Returns the output from running g.mlist, as a list of qualified
  793. names.
  794. @param type element type (rast, vect, rast3d, region, ...)
  795. @param pattern pattern string
  796. @param mapset mapset name (if not given use search path)
  797. @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or '' (glob pattern)
  798. @return list of elements
  799. """
  800. if type == 'raster' or type == 'cell':
  801. verbose(_('Element type should be "rast" and not "%s"') % type)
  802. type = 'rast'
  803. result = list()
  804. for line in read_command("g.mlist",
  805. quiet = True,
  806. flags = 'm' + flag,
  807. type = type,
  808. pattern = pattern,
  809. mapset = mapset).splitlines():
  810. result.append(line.strip())
  811. return result
  812. def mlist_pairs(type, pattern = None, mapset = None, flag = ''):
  813. """!List of elements as pairs
  814. Returns the output from running g.mlist, as a list of
  815. (name, mapset) pairs
  816. @param type element type (rast, vect, rast3d, region, ...)
  817. @param pattern pattern string
  818. @param mapset mapset name (if not given use search path)
  819. @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or '' (glob pattern)
  820. @return list of elements
  821. """
  822. return [tuple(map.split('@', 1)) for map in mlist_strings(type, pattern, mapset, flag)]
  823. def mlist_grouped(type, pattern = None, check_search_path = True, flag = ''):
  824. """!List of elements grouped by mapsets.
  825. Returns the output from running g.mlist, as a dictionary where the
  826. keys are mapset names and the values are lists of maps in that
  827. mapset. Example:
  828. @code
  829. >>> grass.mlist_grouped('rast', pattern='r*')['PERMANENT']
  830. ['railroads', 'roads', 'rstrct.areas', 'rushmore']
  831. @endcode
  832. @param type element type (rast, vect, rast3d, region, ...)
  833. @param pattern pattern string
  834. @param check_search_path True to add mapsets for the search path with no found elements
  835. @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or '' (glob pattern)
  836. @return directory of mapsets/elements
  837. """
  838. if type == 'raster' or type == 'cell':
  839. verbose(_('Element type should be "rast" and not "%s"') % type)
  840. type = 'rast'
  841. result = {}
  842. if check_search_path:
  843. for mapset in mapsets(search_path = True):
  844. result[mapset] = []
  845. mapset = None
  846. for line in read_command("g.mlist", quiet = True, flags = "m" + flag,
  847. type = type, pattern = pattern).splitlines():
  848. try:
  849. name, mapset = line.split('@')
  850. except ValueError:
  851. warning(_("Invalid element '%s'") % line)
  852. continue
  853. if mapset in result:
  854. result[mapset].append(name)
  855. else:
  856. result[mapset] = [name, ]
  857. return result
  858. # color parsing
  859. named_colors = {
  860. "white": (1.00, 1.00, 1.00),
  861. "black": (0.00, 0.00, 0.00),
  862. "red": (1.00, 0.00, 0.00),
  863. "green": (0.00, 1.00, 0.00),
  864. "blue": (0.00, 0.00, 1.00),
  865. "yellow": (1.00, 1.00, 0.00),
  866. "magenta": (1.00, 0.00, 1.00),
  867. "cyan": (0.00, 1.00, 1.00),
  868. "aqua": (0.00, 0.75, 0.75),
  869. "grey": (0.75, 0.75, 0.75),
  870. "gray": (0.75, 0.75, 0.75),
  871. "orange": (1.00, 0.50, 0.00),
  872. "brown": (0.75, 0.50, 0.25),
  873. "purple": (0.50, 0.00, 1.00),
  874. "violet": (0.50, 0.00, 1.00),
  875. "indigo": (0.00, 0.50, 1.00)}
  876. def parse_color(val, dflt = None):
  877. """!Parses the string "val" as a GRASS colour, which can be either one of
  878. the named colours or an R:G:B tuple e.g. 255:255:255. Returns an
  879. (r,g,b) triple whose components are floating point values between 0
  880. and 1. Example:
  881. \code
  882. >>> grass.parse_color("red")
  883. (1.0, 0.0, 0.0)
  884. >>> grass.parse_color("255:0:0")
  885. (1.0, 0.0, 0.0)
  886. \endcode
  887. @param val color value
  888. @param dflt default color value
  889. @return tuple RGB
  890. """
  891. if val in named_colors:
  892. return named_colors[val]
  893. vals = val.split(':')
  894. if len(vals) == 3:
  895. return tuple(float(v) / 255 for v in vals)
  896. return dflt
  897. # check GRASS_OVERWRITE
  898. def overwrite():
  899. """!Return True if existing files may be overwritten"""
  900. owstr = 'GRASS_OVERWRITE'
  901. return owstr in os.environ and os.environ[owstr] != '0'
  902. # check GRASS_VERBOSE
  903. def verbosity():
  904. """!Return the verbosity level selected by GRASS_VERBOSE"""
  905. vbstr = os.getenv('GRASS_VERBOSE')
  906. if vbstr:
  907. return int(vbstr)
  908. else:
  909. return 2
  910. ## various utilities, not specific to GRASS
  911. # basename inc. extension stripping
  912. def basename(path, ext = None):
  913. """!Remove leading directory components and an optional extension
  914. from the specified path
  915. @param path path
  916. @param ext extension
  917. """
  918. name = os.path.basename(path)
  919. if not ext:
  920. return name
  921. fs = name.rsplit('.', 1)
  922. if len(fs) > 1 and fs[1].lower() == ext:
  923. name = fs[0]
  924. return name
  925. # find a program (replacement for "which")
  926. def find_program(pgm, args = []):
  927. """!Attempt to run a program, with optional arguments.
  928. @param pgm program name
  929. @param args list of arguments
  930. @return False if the attempt failed due to a missing executable
  931. @return True otherwise
  932. """
  933. nuldev = file(os.devnull, 'w+')
  934. try:
  935. ret = call([pgm] + args, stdin = nuldev, stdout = nuldev, stderr = nuldev)
  936. if ret == 0:
  937. found = True
  938. else:
  939. found = False
  940. except:
  941. found = False
  942. nuldev.close()
  943. return found
  944. # try to remove a file, without complaints
  945. def try_remove(path):
  946. """!Attempt to remove a file; no exception is generated if the
  947. attempt fails.
  948. @param path path to file to remove
  949. """
  950. try:
  951. os.remove(path)
  952. except:
  953. pass
  954. # try to remove a directory, without complaints
  955. def try_rmdir(path):
  956. """!Attempt to remove a directory; no exception is generated if the
  957. attempt fails.
  958. @param path path to directory to remove
  959. """
  960. try:
  961. os.rmdir(path)
  962. except:
  963. shutil.rmtree(path, ignore_errors = True)
  964. def float_or_dms(s):
  965. """!Convert DMS to float.
  966. @param s DMS value
  967. @return float value
  968. """
  969. return sum(float(x) / 60 ** n for (n, x) in enumerate(s.split(':')))
  970. # interface to g.mapsets
  971. def mapsets(search_path = False):
  972. """!List available mapsets
  973. @param search_path True to list mapsets only in search path
  974. @return list of mapsets
  975. """
  976. if search_path:
  977. flags = 'p'
  978. else:
  979. flags = 'l'
  980. mapsets = read_command('g.mapsets',
  981. flags = flags,
  982. sep = 'newline',
  983. quiet = True)
  984. if not mapsets:
  985. fatal(_("Unable to list mapsets"))
  986. return mapsets.splitlines()
  987. # interface to `g.proj -c`
  988. def create_location(dbase, location,
  989. epsg = None, proj4 = None, filename = None, wkt = None,
  990. datum = None, datum_trans = None, desc = None):
  991. """!Create new location
  992. Raise ScriptError on error.
  993. @param dbase path to GRASS database
  994. @param location location name to create
  995. @param epsg if given create new location based on EPSG code
  996. @param proj4 if given create new location based on Proj4 definition
  997. @param filename if given create new location based on georeferenced file
  998. @param wkt if given create new location based on WKT definition (path to PRJ file)
  999. @param datum GRASS format datum code
  1000. @param datum_trans datum transformation parameters (used for epsg and proj4)
  1001. @param desc description of the location (creates MYNAME file)
  1002. """
  1003. gisdbase = None
  1004. if epsg or proj4 or filename or wkt:
  1005. # FIXME: changing GISDBASE mid-session is not background-job safe
  1006. gisdbase = gisenv()['GISDBASE']
  1007. run_command('g.gisenv',
  1008. set = 'GISDBASE=%s' % dbase)
  1009. if not os.path.exists(dbase):
  1010. os.mkdir(dbase)
  1011. kwargs = dict()
  1012. if datum:
  1013. kwargs['datum'] = datum
  1014. if datum_trans:
  1015. kwargs['datum_trans'] = datum_trans
  1016. if epsg:
  1017. ps = pipe_command('g.proj',
  1018. quiet = True,
  1019. flags = 't',
  1020. epsg = epsg,
  1021. location = location,
  1022. stderr = PIPE,
  1023. **kwargs)
  1024. elif proj4:
  1025. ps = pipe_command('g.proj',
  1026. quiet = True,
  1027. flags = 't',
  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))
  1127. def legal_name(s):
  1128. """!Checks if the string contains only allowed characters.
  1129. This is the Python implementation of G_legal_filename() function.
  1130. @note It is not clear when to use this function.
  1131. """
  1132. if not s or s[0] == '.':
  1133. warning(_("Illegal filename <%s>. Cannot be 'NULL' or start with '.'.") % s)
  1134. return False
  1135. illegal = [c
  1136. for c in s
  1137. if c in '/"\'@,=*~' or c <= ' ' or c >= '\177']
  1138. if illegal:
  1139. illegal = ''.join(sorted(set(illegal)))
  1140. warning(_("Illegal filename <%s>. <%s> not allowed.\n") % (s, illegal))
  1141. return False
  1142. return True