core.py 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818
  1. """
  2. Core functions to be used in Python scripts.
  3. Usage:
  4. ::
  5. from grass.script import core as grass
  6. grass.parser()
  7. (C) 2008-2014 by the GRASS Development Team
  8. This program is free software under the GNU General Public
  9. License (>=v2). Read the file COPYING that comes with GRASS
  10. for details.
  11. .. sectionauthor:: Glynn Clements
  12. .. sectionauthor:: Martin Landa <landa.martin gmail.com>
  13. .. sectionauthor:: Michael Barton <michael.barton asu.edu>
  14. """
  15. from __future__ import absolute_import, print_function
  16. import os
  17. import sys
  18. import atexit
  19. import subprocess
  20. import shutil
  21. import codecs
  22. import string
  23. import random
  24. import pipes
  25. from tempfile import NamedTemporaryFile
  26. import types as python_types
  27. from .utils import KeyValue, parse_key_val, basename, encode, decode, try_remove
  28. from grass.exceptions import ScriptError, CalledModuleError
  29. # PY2/PY3 compat
  30. if sys.version_info.major >= 3:
  31. unicode = str
  32. # subprocess wrapper that uses shell on Windows
  33. class Popen(subprocess.Popen):
  34. _builtin_exts = set(['.com', '.exe', '.bat', '.cmd'])
  35. @staticmethod
  36. def _escape_for_shell(arg):
  37. # TODO: what are cmd.exe's parsing rules?
  38. return arg
  39. def __init__(self, args, **kwargs):
  40. if (sys.platform == 'win32'
  41. and isinstance(args, list)
  42. and not kwargs.get('shell', False)
  43. and kwargs.get('executable') is None):
  44. cmd = shutil_which(args[0])
  45. if cmd is None:
  46. raise OSError(_("Cannot find the executable {0}")
  47. .format(args[0]))
  48. args = [cmd] + args[1:]
  49. name, ext = os.path.splitext(cmd)
  50. if ext.lower() not in self._builtin_exts:
  51. kwargs['shell'] = True
  52. args = [self._escape_for_shell(arg) for arg in args]
  53. subprocess.Popen.__init__(self, args, **kwargs)
  54. PIPE = subprocess.PIPE
  55. STDOUT = subprocess.STDOUT
  56. raise_on_error = False # raise exception instead of calling fatal()
  57. _capture_stderr = False # capture stderr of subprocesses if possible
  58. def call(*args, **kwargs):
  59. return Popen(*args, **kwargs).wait()
  60. # GRASS-oriented interface to subprocess module
  61. _popen_args = ["bufsize", "executable", "stdin", "stdout", "stderr",
  62. "preexec_fn", "close_fds", "cwd", "env",
  63. "universal_newlines", "startupinfo", "creationflags"]
  64. def _make_val(val):
  65. """Convert value to unicode"""
  66. if isinstance(val, (bytes, str, unicode)):
  67. return decode(val)
  68. if isinstance(val, (int, float)):
  69. return unicode(val)
  70. try:
  71. return ",".join(map(_make_val, iter(val)))
  72. except TypeError:
  73. pass
  74. return unicode(val)
  75. def _make_unicode(val, enc):
  76. """Convert value to unicode with given encoding
  77. :param val: value to be converted
  78. :param enc: encoding to be used
  79. """
  80. if val is None or enc is None:
  81. return val
  82. else:
  83. if enc == 'default':
  84. return decode(val)
  85. else:
  86. return decode(val, encoding=enc)
  87. def get_commands():
  88. """Create list of available GRASS commands to use when parsing
  89. string from the command line
  90. :return: list of commands (set) and directory of scripts (collected
  91. by extension - MS Windows only)
  92. >>> cmds = list(get_commands()[0])
  93. >>> cmds.sort()
  94. >>> cmds[:5]
  95. ['d.barscale', 'd.colorlist', 'd.colortable', 'd.correlate', 'd.erase']
  96. """
  97. gisbase = os.environ['GISBASE']
  98. cmd = list()
  99. scripts = {'.py': list()} if sys.platform == 'win32' else {}
  100. def scan(gisbase, directory):
  101. dir_path = os.path.join(gisbase, directory)
  102. if os.path.exists(dir_path):
  103. for fname in os.listdir(os.path.join(gisbase, directory)):
  104. if scripts: # win32
  105. name, ext = os.path.splitext(fname)
  106. if ext != '.manifest':
  107. cmd.append(name)
  108. if ext in scripts.keys():
  109. scripts[ext].append(name)
  110. else:
  111. cmd.append(fname)
  112. for directory in ('bin', 'scripts'):
  113. scan(gisbase, directory)
  114. # scan gui/scripts/
  115. gui_path = os.path.join(gisbase, 'etc', 'gui', 'scripts')
  116. if os.path.exists(gui_path):
  117. os.environ["PATH"] = os.getenv("PATH") + os.pathsep + gui_path
  118. cmd = cmd + os.listdir(gui_path)
  119. return set(cmd), scripts
  120. # TODO: Please replace this function with shutil.which() before 8.0 comes out
  121. # replacement for which function from shutil (not available in all versions)
  122. # from http://hg.python.org/cpython/file/6860263c05b3/Lib/shutil.py#l1068
  123. # added because of Python scripts running Python scripts on MS Windows
  124. # see also ticket #2008 which is unrelated but same function was proposed
  125. def shutil_which(cmd, mode=os.F_OK | os.X_OK, path=None):
  126. """Given a command, mode, and a PATH string, return the path which
  127. conforms to the given mode on the PATH, or None if there is no such
  128. file.
  129. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
  130. of os.environ.get("PATH"), or can be overridden with a custom search
  131. path.
  132. :param cmd: the command
  133. :param mode:
  134. :param path:
  135. """
  136. # Check that a given file can be accessed with the correct mode.
  137. # Additionally check that `file` is not a directory, as on Windows
  138. # directories pass the os.access check.
  139. def _access_check(fn, mode):
  140. return (os.path.exists(fn) and os.access(fn, mode)
  141. and not os.path.isdir(fn))
  142. # If we're given a path with a directory part, look it up directly rather
  143. # than referring to PATH directories. This includes checking relative to the
  144. # current directory, e.g. ./script
  145. if os.path.dirname(cmd):
  146. if _access_check(cmd, mode):
  147. return cmd
  148. return None
  149. if path is None:
  150. path = os.environ.get("PATH", os.defpath)
  151. if not path:
  152. return None
  153. path = path.split(os.pathsep)
  154. if sys.platform == "win32":
  155. # The current directory takes precedence on Windows.
  156. if os.curdir not in path:
  157. path.insert(0, os.curdir)
  158. # PATHEXT is necessary to check on Windows (force lowercase)
  159. pathext = list(map(lambda x: x.lower(),
  160. os.environ.get("PATHEXT", "").split(os.pathsep)))
  161. if '.py' not in pathext:
  162. # we assume that PATHEXT contains always '.py'
  163. pathext.insert(0, '.py')
  164. # See if the given file matches any of the expected path extensions.
  165. # This will allow us to short circuit when given "python3.exe".
  166. # If it does match, only test that one, otherwise we have to try
  167. # others.
  168. if any(cmd.lower().endswith(ext) for ext in pathext):
  169. files = [cmd]
  170. else:
  171. files = [cmd + ext for ext in pathext]
  172. else:
  173. # On other platforms you don't have things like PATHEXT to tell you
  174. # what file suffixes are executable, so just pass on cmd as-is.
  175. files = [cmd]
  176. seen = set()
  177. for dir in path:
  178. normdir = os.path.normcase(dir)
  179. if normdir not in seen:
  180. seen.add(normdir)
  181. for thefile in files:
  182. name = os.path.join(dir, thefile)
  183. if _access_check(name, mode):
  184. return name
  185. return None
  186. if sys.version_info.major >= 3:
  187. # Use shutil.which in Python 3, not the custom implementation.
  188. shutil_which = shutil.which # noqa: F811
  189. # Added because of scripts calling scripts on MS Windows.
  190. # Module name (here cmd) differs from the file name (does not have extension).
  191. # Additionally, we don't run scripts using system executable mechanism,
  192. # so we need the full path name.
  193. # However, scripts are on the PATH and '.PY' in in PATHEXT, so we can use
  194. # shutil.which to get the full file path. Addons are on PATH too.
  195. # An alternative to which function call would be to check the script path and
  196. # addons path. This is proposed improvement for the future.
  197. # Another alternative is to check some global list of scripts but this list
  198. # needs to be created first. The question is what is less expensive.
  199. # Note that getting the full path is only part of the solution,
  200. # the other part is to use the right Python as an executable and pass the full
  201. # script path as a parameter.
  202. # Nevertheless, it is unclear on which places which extensions are added.
  203. # This function also could skip the check for platform but depends
  204. # how will be used, this is most general but not most effective.
  205. def get_real_command(cmd):
  206. """Returns the real file command for a module (cmd)
  207. For Python scripts on MS Windows it returns full path to the script
  208. and adds a '.py' extension.
  209. For other cases it just returns a module (name).
  210. So, you can just use this function for all without further check.
  211. >>> get_real_command('g.region')
  212. 'g.region'
  213. :param cmd: the command
  214. """
  215. if sys.platform == 'win32':
  216. # we in fact expect pure module name (without extension)
  217. # so, lets remove extension
  218. if os.path.splitext(cmd)[1] == '.py':
  219. cmd = cmd[:-3]
  220. # PATHEXT is necessary to check on Windows (force lowercase)
  221. pathext = list(map(lambda x: x.lower(),
  222. os.environ['PATHEXT'].split(os.pathsep)))
  223. if '.py' not in pathext:
  224. # we assume that PATHEXT contains always '.py'
  225. os.environ['PATHEXT'] = '.py;' + os.environ['PATHEXT']
  226. full_path = shutil_which(cmd + '.py')
  227. if full_path:
  228. return full_path
  229. return cmd
  230. def make_command(prog, flags="", overwrite=False, quiet=False, verbose=False,
  231. superquiet=False, errors=None, **options):
  232. """Return a list of strings suitable for use as the args parameter to
  233. Popen() or call(). Example:
  234. >>> make_command("g.message", flags = 'w', message = 'this is a warning')
  235. ['g.message', '-w', 'message=this is a warning']
  236. :param str prog: GRASS module
  237. :param str flags: flags to be used (given as a string)
  238. :param bool overwrite: True to enable overwriting the output (<tt>--o</tt>)
  239. :param bool quiet: True to run quietly (<tt>--q</tt>)
  240. :param bool verbose: True to run verbosely (<tt>--v</tt>)
  241. :param options: module's parameters
  242. :return: list of arguments
  243. """
  244. args = [_make_val(prog)]
  245. if overwrite:
  246. args.append("--o")
  247. if quiet:
  248. args.append("--q")
  249. if verbose:
  250. args.append("--v")
  251. if superquiet:
  252. args.append("--qq")
  253. if flags:
  254. flags = _make_val(flags)
  255. if '-' in flags:
  256. raise ScriptError("'-' is not a valid flag")
  257. args.append("-" + flags)
  258. for opt, val in options.items():
  259. if opt in _popen_args:
  260. continue
  261. # convert string to bytes
  262. if val is not None:
  263. if opt.startswith('_'):
  264. opt = opt[1:]
  265. warning(_("To run the module <%s> add underscore at the end"
  266. " of the option <%s> to avoid conflict with Python"
  267. " keywords. Underscore at the beginning is"
  268. " depreciated in GRASS GIS 7.0 and will be removed"
  269. " in version 7.1.") % (prog, opt))
  270. elif opt.endswith('_'):
  271. opt = opt[:-1]
  272. args.append(opt + '=' + _make_val(val))
  273. return args
  274. def handle_errors(returncode, result, args, kwargs):
  275. """Error handler for :func:`run_command()` and similar functions
  276. The function returns *result* if *returncode* is equal to 0,
  277. otherwise it reports errors based on the current settings.
  278. The functions which are using this function to handle errors,
  279. can be typically called with an *errors* parameter.
  280. This function can handle one of the following values: raise,
  281. fatal, status, exit, and ignore. The value raise is a default.
  282. If *kwargs* dictionary contains key ``errors``, the value is used
  283. to determine the behavior on error.
  284. The value ``errors="raise"`` is a default in which case a
  285. ``CalledModuleError`` exception is raised.
  286. For ``errors="fatal"``, the function calls :func:`fatal()`
  287. which has its own rules on what happens next.
  288. For ``errors="status"``, the *returncode* will be returned.
  289. This is useful, e.g., for cases when the exception-based error
  290. handling mechanism is not desirable or the return code has some
  291. meaning not necessarily interpreted as an error by the caller.
  292. For ``errors="exit"``, ``sys.exit()`` is called with the
  293. *returncode*, so it behaves similarly to a Bash script with
  294. ``set -e``. No additional error message or exception is produced.
  295. This might be useful for a simple script where error message
  296. produced by the called module provides sufficient information about
  297. what happened to the end user.
  298. Finally, for ``errors="ignore"``, the value of *result* will be
  299. passed in any case regardless of the *returncode*.
  300. """
  301. def get_module_and_code(args, kwargs):
  302. """Get module name and formatted command"""
  303. # TODO: construction of the whole command is far from perfect
  304. args = make_command(*args, **kwargs)
  305. # Since we are in error handler, let's be extra cautious
  306. # about an empty command.
  307. if args:
  308. module = args[0]
  309. else:
  310. module = None
  311. code = ' '.join(args)
  312. return module, code
  313. if returncode == 0:
  314. return result
  315. handler = kwargs.get('errors', 'raise')
  316. if handler.lower() == 'ignore':
  317. return result
  318. elif handler.lower() == 'status':
  319. return returncode
  320. elif handler.lower() == 'fatal':
  321. module, code = get_module_and_code(args, kwargs)
  322. fatal(_("Module {module} ({code}) failed with"
  323. " non-zero return code {returncode}").format(
  324. module=module, code=code, returncode=returncode))
  325. elif handler.lower() == 'exit':
  326. sys.exit(returncode)
  327. else:
  328. module, code = get_module_and_code(args, kwargs)
  329. raise CalledModuleError(module=module, code=code,
  330. returncode=returncode)
  331. def start_command(prog, flags="", overwrite=False, quiet=False,
  332. verbose=False, superquiet=False, **kwargs):
  333. """Returns a Popen object with the command created by make_command.
  334. Accepts any of the arguments which Popen() accepts apart from "args"
  335. and "shell".
  336. >>> p = start_command("g.gisenv", stdout=subprocess.PIPE)
  337. >>> print(p) # doctest: +ELLIPSIS
  338. <...Popen object at 0x...>
  339. >>> print(p.communicate()[0]) # doctest: +SKIP
  340. GISDBASE='/opt/grass-data';
  341. LOCATION_NAME='spearfish60';
  342. MAPSET='glynn';
  343. GUI='text';
  344. MONITOR='x0';
  345. If the module parameter is the same as Python keyword, add
  346. underscore at the end of the parameter. For example, use
  347. ``lambda_=1.6`` instead of ``lambda=1.6``.
  348. :param str prog: GRASS module
  349. :param str flags: flags to be used (given as a string)
  350. :param bool overwrite: True to enable overwriting the output (<tt>--o</tt>)
  351. :param bool quiet: True to run quietly (<tt>--q</tt>)
  352. :param bool verbose: True to run verbosely (<tt>--v</tt>)
  353. :param kwargs: module's parameters
  354. :return: Popen object
  355. """
  356. if 'encoding' in kwargs.keys():
  357. encoding = kwargs.pop('encoding')
  358. options = {}
  359. popts = {}
  360. for opt, val in kwargs.items():
  361. if opt in _popen_args:
  362. popts[opt] = val
  363. else:
  364. options[opt] = val
  365. args = make_command(prog, flags, overwrite, quiet, verbose, **options)
  366. if debug_level() > 0:
  367. sys.stderr.write("D1/{}: {}.start_command(): {}\n".format(
  368. debug_level(), __name__,
  369. ' '.join(args))
  370. )
  371. sys.stderr.flush()
  372. return Popen(args, **popts)
  373. def run_command(*args, **kwargs):
  374. """Execute a module synchronously
  375. This function passes all arguments to ``start_command()``,
  376. then waits for the process to complete. It is similar to
  377. ``subprocess.check_call()``, but with the :func:`make_command()`
  378. interface. By default, an exception is raised in case of a non-zero
  379. return code by default.
  380. >>> run_command('g.region', raster='elevation')
  381. See :func:`start_command()` for details about parameters and usage.
  382. The behavior on error can be changed using *errors* parameter
  383. which is passed to the :func:`handle_errors()` function.
  384. :param *args: unnamed arguments passed to :func:`start_command()`
  385. :param **kwargs: named arguments passed to :func:`start_command()`
  386. :param str errors: passed to :func:`handle_errors()`
  387. .. versionchanged:: 8.0
  388. Before 8.0, the function was returning 0 when no error occurred
  389. for backward compatibility with code which was checking that
  390. value. Now the function returns None, unless ``errors="status"``
  391. is specified.
  392. .. versionchanged:: 7.2
  393. In 7.0.0, this function was returning the error code. However,
  394. it was rarely checked especially outside of the core code.
  395. Additionally, :func:`read_command()` needed a mechanism to
  396. report errors as it was used more and more in context which
  397. required error handling, Thus, exceptions were introduced as a
  398. more expected default behavior for Python programmers. The
  399. change was backported to 7.0 series.
  400. :raises: ``CalledModuleError`` when module returns non-zero return code
  401. """
  402. encoding = 'default'
  403. if 'encoding' in kwargs:
  404. encoding = kwargs['encoding']
  405. if _capture_stderr and 'stderr' not in kwargs.keys():
  406. kwargs['stderr'] = PIPE
  407. ps = start_command(*args, **kwargs)
  408. if _capture_stderr:
  409. stdout, stderr = ps.communicate()
  410. if encoding is not None:
  411. stdout = _make_unicode(stdout, encoding)
  412. stderr = _make_unicode(stderr, encoding)
  413. returncode = ps.poll()
  414. if returncode:
  415. sys.stderr.write(stderr)
  416. else:
  417. returncode = ps.wait()
  418. return handle_errors(returncode, result=None, args=args, kwargs=kwargs)
  419. def pipe_command(*args, **kwargs):
  420. """Passes all arguments to start_command(), but also adds
  421. "stdout = PIPE". Returns the Popen object.
  422. >>> p = pipe_command("g.gisenv")
  423. >>> print(p) # doctest: +ELLIPSIS
  424. <....Popen object at 0x...>
  425. >>> print(p.communicate()[0]) # doctest: +SKIP
  426. GISDBASE='/opt/grass-data';
  427. LOCATION_NAME='spearfish60';
  428. MAPSET='glynn';
  429. GUI='text';
  430. MONITOR='x0';
  431. :param list args: list of unnamed arguments (see start_command() for details)
  432. :param list kwargs: list of named arguments (see start_command() for details)
  433. :return: Popen object
  434. """
  435. kwargs['stdout'] = PIPE
  436. return start_command(*args, **kwargs)
  437. def feed_command(*args, **kwargs):
  438. """Passes all arguments to start_command(), but also adds
  439. "stdin = PIPE". Returns the Popen object.
  440. :param list args: list of unnamed arguments (see start_command() for details)
  441. :param list kwargs: list of named arguments (see start_command() for details)
  442. :return: Popen object
  443. """
  444. kwargs['stdin'] = PIPE
  445. return start_command(*args, **kwargs)
  446. def read_command(*args, **kwargs):
  447. """Passes all arguments to pipe_command, then waits for the process to
  448. complete, returning its stdout (i.e. similar to shell `backticks`).
  449. The behavior on error can be changed using *errors* parameter
  450. which is passed to the :func:`handle_errors()` function.
  451. :param list args: list of unnamed arguments (see start_command() for details)
  452. :param list kwargs: list of named arguments (see start_command() for details)
  453. :return: stdout
  454. """
  455. encoding = 'default'
  456. if 'encoding' in kwargs:
  457. encoding = kwargs['encoding']
  458. if _capture_stderr and 'stderr' not in kwargs.keys():
  459. kwargs['stderr'] = PIPE
  460. process = pipe_command(*args, **kwargs)
  461. stdout, stderr = process.communicate()
  462. if encoding is not None:
  463. stdout = _make_unicode(stdout, encoding)
  464. stderr = _make_unicode(stderr, encoding)
  465. returncode = process.poll()
  466. if _capture_stderr and returncode:
  467. sys.stderr.write(stderr)
  468. return handle_errors(returncode, stdout, args, kwargs)
  469. def parse_command(*args, **kwargs):
  470. """Passes all arguments to read_command, then parses the output
  471. by parse_key_val().
  472. Parsing function can be optionally given by <em>parse</em> parameter
  473. including its arguments, e.g.
  474. ::
  475. parse_command(..., parse = (grass.parse_key_val, { 'sep' : ':' }))
  476. or you can simply define <em>delimiter</em>
  477. ::
  478. parse_command(..., delimiter = ':')
  479. :param args: list of unnamed arguments (see start_command() for details)
  480. :param kwargs: list of named arguments (see start_command() for details)
  481. :return: parsed module output
  482. """
  483. parse = None
  484. parse_args = {}
  485. if 'parse' in kwargs:
  486. if isinstance(kwargs['parse'], tuple):
  487. parse = kwargs['parse'][0]
  488. parse_args = kwargs['parse'][1]
  489. del kwargs['parse']
  490. if 'delimiter' in kwargs:
  491. parse_args = {'sep': kwargs['delimiter']}
  492. del kwargs['delimiter']
  493. if not parse:
  494. parse = parse_key_val # use default fn
  495. res = read_command(*args, **kwargs)
  496. return parse(res, **parse_args)
  497. def write_command(*args, **kwargs):
  498. """Execute a module with standard input given by *stdin* parameter.
  499. Passes all arguments to ``feed_command()``, with the string specified
  500. by the *stdin* argument fed to the process' standard input.
  501. >>> write_command(
  502. ... 'v.in.ascii', input='-',
  503. ... stdin='%s|%s' % (635818.8, 221342.4),
  504. ... output='view_point')
  505. 0
  506. See ``start_command()`` for details about parameters and usage.
  507. The behavior on error can be changed using *errors* parameter
  508. which is passed to the :func:`handle_errors()` function.
  509. :param *args: unnamed arguments passed to ``start_command()``
  510. :param **kwargs: named arguments passed to ``start_command()``
  511. :returns: 0 with default parameters for backward compatibility only
  512. :raises: ``CalledModuleError`` when module returns non-zero return code
  513. """
  514. encoding = 'default'
  515. if 'encoding' in kwargs:
  516. encoding = kwargs['encoding']
  517. # TODO: should we delete it from kwargs?
  518. stdin = kwargs['stdin']
  519. if encoding is None or encoding == 'default':
  520. stdin = encode(stdin)
  521. else:
  522. stdin = encode(stdin, encoding=encoding)
  523. if _capture_stderr and 'stderr' not in kwargs.keys():
  524. kwargs['stderr'] = PIPE
  525. process = feed_command(*args, **kwargs)
  526. unused, stderr = process.communicate(stdin)
  527. if encoding is not None:
  528. unused = _make_unicode(unused, encoding)
  529. stderr = _make_unicode(stderr, encoding)
  530. returncode = process.poll()
  531. if _capture_stderr and returncode:
  532. sys.stderr.write(stderr)
  533. return handle_errors(returncode, returncode, args, kwargs)
  534. def exec_command(prog, flags="", overwrite=False, quiet=False, verbose=False,
  535. superquiet=False, env=None, **kwargs):
  536. """Interface to os.execvpe(), but with the make_command() interface.
  537. :param str prog: GRASS module
  538. :param str flags: flags to be used (given as a string)
  539. :param bool overwrite: True to enable overwriting the output (<tt>--o</tt>)
  540. :param bool quiet: True to run quietly (<tt>--q</tt>)
  541. :param bool verbose: True to run verbosely (<tt>--v</tt>)
  542. :param env: directory with environmental variables
  543. :param list kwargs: module's parameters
  544. """
  545. args = make_command(prog, flags, overwrite, quiet, verbose, **kwargs)
  546. if env is None:
  547. env = os.environ
  548. os.execvpe(prog, args, env)
  549. # interface to g.message
  550. def message(msg, flag=None):
  551. """Display a message using `g.message`
  552. :param str msg: message to be displayed
  553. :param str flag: flags (given as string)
  554. """
  555. run_command("g.message", flags=flag, message=msg, errors='ignore')
  556. def debug(msg, debug=1):
  557. """Display a debugging message using `g.message -d`
  558. :param str msg: debugging message to be displayed
  559. :param str debug: debug level (0-5)
  560. """
  561. if debug_level() >= debug:
  562. # TODO: quite a random hack here, do we need it somewhere else too?
  563. if sys.platform == "win32":
  564. msg = msg.replace('&', '^&')
  565. run_command("g.message", flags='d', message=msg, debug=debug)
  566. def verbose(msg):
  567. """Display a verbose message using `g.message -v`
  568. :param str msg: verbose message to be displayed
  569. """
  570. message(msg, flag='v')
  571. def info(msg):
  572. """Display an informational message using `g.message -i`
  573. :param str msg: informational message to be displayed
  574. """
  575. message(msg, flag='i')
  576. def percent(i, n, s):
  577. """Display a progress info message using `g.message -p`
  578. ::
  579. message(_("Percent complete..."))
  580. n = 100
  581. for i in range(n):
  582. percent(i, n, 1)
  583. percent(1, 1, 1)
  584. :param int i: current item
  585. :param int n: total number of items
  586. :param int s: increment size
  587. """
  588. message("%d %d %d" % (i, n, s), flag='p')
  589. def warning(msg):
  590. """Display a warning message using `g.message -w`
  591. :param str msg: warning message to be displayed
  592. """
  593. message(msg, flag='w')
  594. def error(msg):
  595. """Display an error message using `g.message -e`
  596. This function does not end the execution of the program.
  597. The right action after the error is up to the caller.
  598. For error handling using the standard mechanism use :func:`fatal()`.
  599. :param str msg: error message to be displayed
  600. """
  601. message(msg, flag='e')
  602. def fatal(msg):
  603. """Display an error message using `g.message -e`, then abort or raise
  604. Raises exception when module global raise_on_error is 'True', abort
  605. (calls exit) otherwise.
  606. Use :func:`set_raise_on_error()` to set the behavior.
  607. :param str msg: error message to be displayed
  608. """
  609. global raise_on_error
  610. if raise_on_error:
  611. raise ScriptError(msg)
  612. error(msg)
  613. sys.exit(1)
  614. def set_raise_on_error(raise_exp=True):
  615. """Define behaviour on fatal error (fatal() called)
  616. :param bool raise_exp: True to raise ScriptError instead of calling
  617. sys.exit(1) in fatal()
  618. :return: current status
  619. """
  620. global raise_on_error
  621. tmp_raise = raise_on_error
  622. raise_on_error = raise_exp
  623. return tmp_raise
  624. def get_raise_on_error():
  625. """Return True if a ScriptError exception is raised instead of calling
  626. sys.exit(1) in case a fatal error was invoked with fatal()
  627. """
  628. global raise_on_error
  629. return raise_on_error
  630. # TODO: solve also warnings (not printed now)
  631. def set_capture_stderr(capture=True):
  632. """Enable capturing standard error output of modules and print it.
  633. By default, standard error output (stderr) of child processes shows
  634. in the same place as output of the parent process. This may not
  635. always be the same place as ``sys.stderr`` is written.
  636. After calling this function, functions in the ``grass.script``
  637. package will capture the stderr of child processes and pass it
  638. to ``sys.stderr`` if there is an error.
  639. .. note::
  640. This is advantages for interactive shells such as the one in GUI
  641. and interactive notebooks such as Jupyer Notebook.
  642. The capturing can be applied only in certain cases, for example
  643. in case of run_command() it is applied because run_command() nor
  644. its callers do not handle the streams, however feed_command()
  645. cannot do capturing because its callers handle the streams.
  646. The previous state is returned. Passing ``False`` disables the
  647. capturing.
  648. .. versionadded:: 7.4
  649. """
  650. global _capture_stderr
  651. tmp = _capture_stderr
  652. _capture_stderr = capture
  653. return tmp
  654. def get_capture_stderr():
  655. """Return True if stderr is captured, False otherwise.
  656. See set_capture_stderr().
  657. """
  658. global _capture_stderr
  659. return _capture_stderr
  660. # interface to g.parser
  661. def _parse_opts(lines):
  662. options = {}
  663. flags = {}
  664. for line in lines:
  665. if not line:
  666. break
  667. try:
  668. [var, val] = line.split(b'=', 1)
  669. [var, val] = [decode(var), decode(val)]
  670. except:
  671. raise SyntaxError("invalid output from g.parser: %s" % line)
  672. if var.startswith('flag_'):
  673. flags[var[5:]] = bool(int(val))
  674. elif var.startswith('opt_'):
  675. options[var[4:]] = val
  676. elif var in ['GRASS_OVERWRITE', 'GRASS_VERBOSE']:
  677. os.environ[var] = val
  678. else:
  679. raise SyntaxError("invalid output from g.parser: %s" % line)
  680. return (options, flags)
  681. def parser():
  682. """Interface to g.parser, intended to be run from the top-level, e.g.:
  683. ::
  684. if __name__ == "__main__":
  685. options, flags = grass.parser()
  686. main()
  687. Thereafter, the global variables "options" and "flags" will be
  688. dictionaries containing option/flag values, keyed by lower-case
  689. option/flag names. The values in "options" are strings, those in
  690. "flags" are Python booleans.
  691. Overview table of parser standard options:
  692. https://grass.osgeo.org/grass79/manuals/parser_standard_options.html
  693. """
  694. if not os.getenv("GISBASE"):
  695. print("You must be in GRASS GIS to run this program.", file=sys.stderr)
  696. sys.exit(1)
  697. cmdline = [basename(sys.argv[0])]
  698. cmdline += [pipes.quote(a) for a in sys.argv[1:]]
  699. os.environ['CMDLINE'] = ' '.join(cmdline)
  700. argv = sys.argv[:]
  701. name = argv[0]
  702. if not os.path.isabs(name):
  703. if os.sep in name or (os.altsep and os.altsep in name):
  704. argv[0] = os.path.abspath(name)
  705. else:
  706. argv[0] = os.path.join(sys.path[0], name)
  707. prog = "g.parser.exe" if sys.platform == "win32" else "g.parser"
  708. p = subprocess.Popen([prog, '-n'] + argv, stdout=subprocess.PIPE)
  709. s = p.communicate()[0]
  710. lines = s.split(b'\0')
  711. if not lines or lines[0] != b"@ARGS_PARSED@":
  712. stdout = os.fdopen(sys.stdout.fileno(), 'wb')
  713. stdout.write(s)
  714. sys.exit(p.returncode)
  715. return _parse_opts(lines[1:])
  716. # interface to g.tempfile
  717. def tempfile(create=True, env=None):
  718. """Returns the name of a temporary file, created with g.tempfile.
  719. :param bool create: True to create a file
  720. :param env: environment
  721. :return: path to a tmp file
  722. """
  723. flags = ''
  724. if not create:
  725. flags += 'd'
  726. return read_command("g.tempfile", flags=flags, pid=os.getpid(), env=env).strip()
  727. def tempdir(env=None):
  728. """Returns the name of a temporary dir, created with g.tempfile."""
  729. tmp = tempfile(create=False, env=env)
  730. os.mkdir(tmp)
  731. return tmp
  732. def tempname(length, lowercase=False):
  733. """Generate a GRASS and SQL compliant random name starting with tmp_
  734. followed by a random part of length "length"
  735. :param int length: length of the random part of the name to generate
  736. :param bool lowercase: use only lowercase characters to generate name
  737. :returns: String with a random name of length "length" starting with a letter
  738. :rtype: str
  739. :Example:
  740. >>> tempname(12)
  741. 'tmp_MxMa1kAS13s9'
  742. """
  743. chars = string.ascii_lowercase + string.digits
  744. if not lowercase:
  745. chars += string.ascii_uppercase
  746. random_part = ''.join(random.choice(chars) for _ in range(length))
  747. randomname = 'tmp_' + random_part
  748. return randomname
  749. def _compare_projection(dic):
  750. """Check if projection has some possibility of duplicate names like
  751. Universal Transverse Mercator and Universe Transverse Mercator and
  752. unify them
  753. :param dic: The dictionary containing information about projection
  754. :return: The dictionary with the new values if needed
  755. """
  756. # the lookup variable is a list of list, each list contains all the
  757. # possible name for a projection system
  758. lookup = [['Universal Transverse Mercator', 'Universe Transverse Mercator']]
  759. for lo in lookup:
  760. for n in range(len(dic['name'])):
  761. if dic['name'][n] in lo:
  762. dic['name'][n] = lo[0]
  763. return dic
  764. def _compare_units(dic):
  765. """Check if units has some possibility of duplicate names like
  766. meter and metre and unify them
  767. :param dic: The dictionary containing information about units
  768. :return: The dictionary with the new values if needed
  769. """
  770. # the lookup variable is a list of list, each list contains all the
  771. # possible name for a units
  772. lookup = [['meter', 'metre'], ['meters', 'metres'], ['kilometer',
  773. 'kilometre'], ['kilometers', 'kilometres']]
  774. for l in lookup:
  775. for n in range(len(dic['unit'])):
  776. if dic['unit'][n].lower() in l:
  777. dic['unit'][n] = l[0]
  778. for n in range(len(dic['units'])):
  779. if dic['units'][n].lower() in l:
  780. dic['units'][n] = l[0]
  781. return dic
  782. def _text_to_key_value_dict(filename, sep=":", val_sep=",", checkproj=False,
  783. checkunits=False):
  784. """Convert a key-value text file, where entries are separated by newlines
  785. and the key and value are separated by `sep', into a key-value dictionary
  786. and discover/use the correct data types (float, int or string) for values.
  787. :param str filename: The name or name and path of the text file to convert
  788. :param str sep: The character that separates the keys and values, default
  789. is ":"
  790. :param str val_sep: The character that separates the values of a single
  791. key, default is ","
  792. :param bool checkproj: True if it has to check some information about
  793. projection system
  794. :param bool checkproj: True if it has to check some information about units
  795. :return: The dictionary
  796. A text file with this content:
  797. ::
  798. a: Hello
  799. b: 1.0
  800. c: 1,2,3,4,5
  801. d : hello,8,0.1
  802. Will be represented as this dictionary:
  803. ::
  804. {'a': ['Hello'], 'c': [1, 2, 3, 4, 5], 'b': [1.0], 'd': ['hello', 8, 0.1]}
  805. """
  806. text = open(filename, "r").readlines()
  807. kvdict = KeyValue()
  808. for line in text:
  809. if line.find(sep) >= 0:
  810. key, value = line.split(sep)
  811. key = key.strip()
  812. value = value.strip()
  813. else:
  814. # Jump over empty values
  815. continue
  816. values = value.split(val_sep)
  817. value_list = []
  818. for value in values:
  819. not_float = False
  820. not_int = False
  821. # Convert values into correct types
  822. # We first try integer then float
  823. try:
  824. value_converted = int(value)
  825. except:
  826. not_int = True
  827. if not_int:
  828. try:
  829. value_converted = float(value)
  830. except:
  831. not_float = True
  832. if not_int and not_float:
  833. value_converted = value.strip()
  834. value_list.append(value_converted)
  835. kvdict[key] = value_list
  836. if checkproj:
  837. kvdict = _compare_projection(kvdict)
  838. if checkunits:
  839. kvdict = _compare_units(kvdict)
  840. return kvdict
  841. def compare_key_value_text_files(filename_a, filename_b, sep=":",
  842. val_sep=",", precision=0.000001,
  843. proj=False, units=False):
  844. """Compare two key-value text files
  845. This method will print a warning in case keys that are present in the first
  846. file are not present in the second one.
  847. The comparison method tries to convert the values into their native format
  848. (float, int or string) to allow correct comparison.
  849. An example key-value text file may have this content:
  850. ::
  851. a: Hello
  852. b: 1.0
  853. c: 1,2,3,4,5
  854. d : hello,8,0.1
  855. :param str filename_a: name of the first key-value text file
  856. :param str filenmae_b: name of the second key-value text file
  857. :param str sep: character that separates the keys and values, default is ":"
  858. :param str val_sep: character that separates the values of a single key, default is ","
  859. :param double precision: precision with which the floating point values are compared
  860. :param bool proj: True if it has to check some information about projection system
  861. :param bool units: True if it has to check some information about units
  862. :return: True if full or almost identical, False if different
  863. """
  864. dict_a = _text_to_key_value_dict(filename_a, sep, checkproj=proj,
  865. checkunits=units)
  866. dict_b = _text_to_key_value_dict(filename_b, sep, checkproj=proj,
  867. checkunits=units)
  868. if sorted(dict_a.keys()) != sorted(dict_b.keys()):
  869. return False
  870. # We compare matching keys
  871. for key in dict_a.keys():
  872. # Floating point values must be handled separately
  873. if isinstance(dict_a[key], float) and isinstance(dict_b[key], float):
  874. if abs(dict_a[key] - dict_b[key]) > precision:
  875. return False
  876. elif isinstance(dict_a[key], float) or isinstance(dict_b[key], float):
  877. warning(_("Mixing value types. Will try to compare after "
  878. "integer conversion"))
  879. return int(dict_a[key]) == int(dict_b[key])
  880. elif key == "+towgs84":
  881. # We compare the sum of the entries
  882. if abs(sum(dict_a[key]) - sum(dict_b[key])) > precision:
  883. return False
  884. else:
  885. if dict_a[key] != dict_b[key]:
  886. return False
  887. return True
  888. # interface to g.gisenv
  889. def gisenv(env=None):
  890. """Returns the output from running g.gisenv (with no arguments), as a
  891. dictionary. Example:
  892. >>> env = gisenv()
  893. >>> print(env['GISDBASE']) # doctest: +SKIP
  894. /opt/grass-data
  895. :param env run with different environment
  896. :return: list of GRASS variables
  897. """
  898. s = read_command("g.gisenv", flags='n', env=env)
  899. return parse_key_val(s)
  900. # interface to g.region
  901. def locn_is_latlong(env=None):
  902. """Tests if location is lat/long. Value is obtained
  903. by checking the "g.region -pu" projection code.
  904. :return: True for a lat/long region, False otherwise
  905. """
  906. s = read_command("g.region", flags='pu', env=env)
  907. kv = parse_key_val(s, ':')
  908. if kv['projection'].split(' ')[0] == '3':
  909. return True
  910. else:
  911. return False
  912. def region(region3d=False, complete=False, env=None):
  913. """Returns the output from running "g.region -gu", as a
  914. dictionary. Example:
  915. :param bool region3d: True to get 3D region
  916. :param bool complete:
  917. :param env env
  918. >>> curent_region = region()
  919. >>> # obtain n, s, e and w values
  920. >>> [curent_region[key] for key in "nsew"] # doctest: +ELLIPSIS
  921. [..., ..., ..., ...]
  922. >>> # obtain ns and ew resulutions
  923. >>> (curent_region['nsres'], curent_region['ewres']) # doctest: +ELLIPSIS
  924. (..., ...)
  925. :return: dictionary of region values
  926. """
  927. flgs = 'gu'
  928. if region3d:
  929. flgs += '3'
  930. if complete:
  931. flgs += 'cep'
  932. s = read_command("g.region", flags=flgs, env=env)
  933. reg = parse_key_val(s, val_type=float)
  934. for k in ['projection', 'zone', 'rows', 'cols', 'cells',
  935. 'rows3', 'cols3', 'cells3', 'depths']:
  936. if k not in reg:
  937. continue
  938. reg[k] = int(reg[k])
  939. return reg
  940. def region_env(region3d=False, flags=None, env=None, **kwargs):
  941. """Returns region settings as a string which can used as
  942. GRASS_REGION environmental variable.
  943. If no 'kwargs' are given then the current region is used. Note
  944. that this function doesn't modify the current region!
  945. See also :func:`use_temp_region()` for alternative method how to define
  946. temporary region used for raster-based computation.
  947. :param bool region3d: True to get 3D region
  948. :param string flags: for example 'a'
  949. :param env: different environment than current
  950. :param kwargs: g.region's parameters like 'raster', 'vector' or 'region'
  951. ::
  952. os.environ['GRASS_REGION'] = grass.region_env(region='detail')
  953. grass.mapcalc('map=1', overwrite=True)
  954. os.environ.pop('GRASS_REGION')
  955. :return: string with region values
  956. :return: empty string on error
  957. """
  958. # read proj/zone from WIND file
  959. gis_env = gisenv(env)
  960. windfile = os.path.join(gis_env['GISDBASE'], gis_env['LOCATION_NAME'],
  961. gis_env['MAPSET'], "WIND")
  962. with open(windfile, "r") as fd:
  963. grass_region = ''
  964. for line in fd.readlines():
  965. key, value = map(lambda x: x.strip(), line.split(":", 1))
  966. if kwargs and key not in ('proj', 'zone'):
  967. continue
  968. if not kwargs and not region3d and \
  969. key in ('top', 'bottom', 'cols3', 'rows3',
  970. 'depths', 'e-w resol3', 'n-s resol3', 't-b resol'):
  971. continue
  972. grass_region += '%s: %s;' % (key, value)
  973. if not kwargs: # return current region
  974. return grass_region
  975. # read other values from `g.region -gu`
  976. flgs = 'ug'
  977. if region3d:
  978. flgs += '3'
  979. if flags:
  980. flgs += flags
  981. s = read_command('g.region', flags=flgs, env=env, **kwargs)
  982. if not s:
  983. return ''
  984. reg = parse_key_val(s)
  985. kwdata = [('north', 'n'),
  986. ('south', 's'),
  987. ('east', 'e'),
  988. ('west', 'w'),
  989. ('cols', 'cols'),
  990. ('rows', 'rows'),
  991. ('e-w resol', 'ewres'),
  992. ('n-s resol', 'nsres')]
  993. if region3d:
  994. kwdata += [('top', 't'),
  995. ('bottom', 'b'),
  996. ('cols3', 'cols3'),
  997. ('rows3', 'rows3'),
  998. ('depths', 'depths'),
  999. ('e-w resol3', 'ewres3'),
  1000. ('n-s resol3', 'nsres3'),
  1001. ('t-b resol', 'tbres')]
  1002. for wkey, rkey in kwdata:
  1003. grass_region += '%s: %s;' % (wkey, reg[rkey])
  1004. return grass_region
  1005. def use_temp_region():
  1006. """Copies the current region to a temporary region with "g.region save=",
  1007. then sets WIND_OVERRIDE to refer to that region. Installs an atexit
  1008. handler to delete the temporary region upon termination.
  1009. """
  1010. name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
  1011. run_command("g.region", flags="u", save=name, overwrite=True)
  1012. os.environ['WIND_OVERRIDE'] = name
  1013. atexit.register(del_temp_region)
  1014. def del_temp_region():
  1015. """Unsets WIND_OVERRIDE and removes any region named by it."""
  1016. try:
  1017. name = os.environ.pop('WIND_OVERRIDE')
  1018. run_command("g.remove", flags='f', quiet=True, type='region', name=name)
  1019. except:
  1020. pass
  1021. # interface to g.findfile
  1022. def find_file(name, element='cell', mapset=None, env=None):
  1023. """Returns the output from running g.findfile as a
  1024. dictionary. Example:
  1025. >>> result = find_file('elevation', element='cell')
  1026. >>> print(result['fullname'])
  1027. elevation@PERMANENT
  1028. >>> print(result['file']) # doctest: +ELLIPSIS
  1029. /.../PERMANENT/cell/elevation
  1030. :param str name: file name
  1031. :param str element: element type (default 'cell')
  1032. :param str mapset: mapset name (default all mapsets in search path)
  1033. :param env: environment
  1034. :return: parsed output of g.findfile
  1035. """
  1036. if element == 'raster' or element == 'rast':
  1037. verbose(_('Element type should be "cell" and not "%s"') % element)
  1038. element = 'cell'
  1039. # g.findfile returns non-zero when file was not found
  1040. # se we ignore return code and just focus on stdout
  1041. process = start_command('g.findfile', flags='n',
  1042. element=element, file=name, mapset=mapset,
  1043. stdout=PIPE, env=env)
  1044. stdout = process.communicate()[0]
  1045. return parse_key_val(stdout)
  1046. # interface to g.list
  1047. def list_strings(type, pattern=None, mapset=None, exclude=None,
  1048. flag='', env=None):
  1049. """List of elements as strings.
  1050. Returns the output from running g.list, as a list of qualified
  1051. names.
  1052. :param str type: element type (raster, vector, raster_3d, region, ...)
  1053. :param str pattern: pattern string
  1054. :param str mapset: mapset name (if not given use search path)
  1055. :param str exclude: pattern string to exclude maps from the research
  1056. :param str flag: pattern type: 'r' (basic regexp), 'e' (extended regexp),
  1057. or '' (glob pattern)
  1058. :param env: environment
  1059. :return: list of elements
  1060. """
  1061. if type == 'cell':
  1062. verbose(_('Element type should be "raster" and not "%s"') % type)
  1063. result = list()
  1064. for line in read_command("g.list",
  1065. quiet=True,
  1066. flags='m' + flag,
  1067. type=type,
  1068. pattern=pattern,
  1069. exclude=exclude,
  1070. mapset=mapset,
  1071. env=env).splitlines():
  1072. result.append(line.strip())
  1073. return result
  1074. def list_pairs(type, pattern=None, mapset=None, exclude=None,
  1075. flag='', env=None):
  1076. """List of elements as pairs
  1077. Returns the output from running g.list, as a list of
  1078. (name, mapset) pairs
  1079. :param str type: element type (raster, vector, raster_3d, region, ...)
  1080. :param str pattern: pattern string
  1081. :param str mapset: mapset name (if not given use search path)
  1082. :param str exclude: pattern string to exclude maps from the research
  1083. :param str flag: pattern type: 'r' (basic regexp), 'e' (extended regexp),
  1084. or '' (glob pattern)
  1085. :param env: environment
  1086. :return: list of elements
  1087. """
  1088. return [tuple(map.split('@', 1)) for map in list_strings(type, pattern,
  1089. mapset, exclude,
  1090. flag, env)]
  1091. def list_grouped(type, pattern=None, check_search_path=True, exclude=None,
  1092. flag='', env=None):
  1093. """List of elements grouped by mapsets.
  1094. Returns the output from running g.list, as a dictionary where the
  1095. keys are mapset names and the values are lists of maps in that
  1096. mapset. Example:
  1097. >>> list_grouped('vect', pattern='*roads*')['PERMANENT']
  1098. ['railroads', 'roadsmajor']
  1099. :param str type: element type (raster, vector, raster_3d, region, ...) or list of elements
  1100. :param str pattern: pattern string
  1101. :param str check_search_path: True to add mapsets for the search path
  1102. with no found elements
  1103. :param str exclude: pattern string to exclude maps from the research
  1104. :param str flag: pattern type: 'r' (basic regexp), 'e' (extended regexp),
  1105. or '' (glob pattern)
  1106. :param env: environment
  1107. :return: directory of mapsets/elements
  1108. """
  1109. if isinstance(type, str) or len(type) == 1:
  1110. types = [type]
  1111. store_types = False
  1112. else:
  1113. types = type
  1114. store_types = True
  1115. flag += 't'
  1116. for i in range(len(types)):
  1117. if types[i] == 'cell':
  1118. verbose(_('Element type should be "raster" and not "%s"') % types[i])
  1119. types[i] = 'raster'
  1120. result = {}
  1121. if check_search_path:
  1122. for mapset in mapsets(search_path=True, env=env):
  1123. if store_types:
  1124. result[mapset] = {}
  1125. else:
  1126. result[mapset] = []
  1127. mapset = None
  1128. for line in read_command("g.list", quiet=True, flags="m" + flag,
  1129. type=types, pattern=pattern,
  1130. exclude=exclude, env=env).splitlines():
  1131. try:
  1132. name, mapset = line.split('@')
  1133. except ValueError:
  1134. warning(_("Invalid element '%s'") % line)
  1135. continue
  1136. if store_types:
  1137. type_, name = name.split('/')
  1138. if mapset in result:
  1139. if type_ in result[mapset]:
  1140. result[mapset][type_].append(name)
  1141. else:
  1142. result[mapset][type_] = [name, ]
  1143. else:
  1144. result[mapset] = {type_: [name, ]}
  1145. else:
  1146. if mapset in result:
  1147. result[mapset].append(name)
  1148. else:
  1149. result[mapset] = [name, ]
  1150. return result
  1151. # color parsing
  1152. named_colors = {
  1153. "white": (1.00, 1.00, 1.00),
  1154. "black": (0.00, 0.00, 0.00),
  1155. "red": (1.00, 0.00, 0.00),
  1156. "green": (0.00, 1.00, 0.00),
  1157. "blue": (0.00, 0.00, 1.00),
  1158. "yellow": (1.00, 1.00, 0.00),
  1159. "magenta": (1.00, 0.00, 1.00),
  1160. "cyan": (0.00, 1.00, 1.00),
  1161. "aqua": (0.00, 0.75, 0.75),
  1162. "grey": (0.75, 0.75, 0.75),
  1163. "gray": (0.75, 0.75, 0.75),
  1164. "orange": (1.00, 0.50, 0.00),
  1165. "brown": (0.75, 0.50, 0.25),
  1166. "purple": (0.50, 0.00, 1.00),
  1167. "violet": (0.50, 0.00, 1.00),
  1168. "indigo": (0.00, 0.50, 1.00)}
  1169. def parse_color(val, dflt=None):
  1170. """Parses the string "val" as a GRASS colour, which can be either one of
  1171. the named colours or an R:G:B tuple e.g. 255:255:255. Returns an
  1172. (r,g,b) triple whose components are floating point values between 0
  1173. and 1. Example:
  1174. >>> parse_color("red")
  1175. (1.0, 0.0, 0.0)
  1176. >>> parse_color("255:0:0")
  1177. (1.0, 0.0, 0.0)
  1178. :param val: color value
  1179. :param dflt: default color value
  1180. :return: tuple RGB
  1181. """
  1182. if val in named_colors:
  1183. return named_colors[val]
  1184. vals = val.split(':')
  1185. if len(vals) == 3:
  1186. return tuple(float(v) / 255 for v in vals)
  1187. return dflt
  1188. # check GRASS_OVERWRITE
  1189. def overwrite():
  1190. """Return True if existing files may be overwritten"""
  1191. owstr = 'GRASS_OVERWRITE'
  1192. return owstr in os.environ and os.environ[owstr] != '0'
  1193. # check GRASS_VERBOSE
  1194. def verbosity():
  1195. """Return the verbosity level selected by GRASS_VERBOSE
  1196. Currently, there are 5 levels of verbosity:
  1197. -1 nothing will be printed (also fatal errors and warnings will be discarded)
  1198. 0 only errors and warnings are printed, triggered by --q or --quiet flag.
  1199. 1 progress information (percent) and important messages will be printed
  1200. 2 all messages will be printed
  1201. 3 also verbose messages will be printed. Triggered by --v or --verbose flag.
  1202. """
  1203. vbstr = os.getenv('GRASS_VERBOSE')
  1204. if vbstr:
  1205. return int(vbstr)
  1206. else:
  1207. return 2
  1208. ## various utilities, not specific to GRASS
  1209. def find_program(pgm, *args):
  1210. """Attempt to run a program, with optional arguments.
  1211. You must call the program in a way that will return a successful
  1212. exit code. For GRASS modules this means you need to pass it some
  1213. valid CLI option, like "--help". For other programs a common
  1214. valid do-little option is usually "--version".
  1215. Example:
  1216. >>> find_program('r.sun', '--help')
  1217. True
  1218. >>> find_program('ls', '--version')
  1219. True
  1220. :param str pgm: program name
  1221. :param args: list of arguments
  1222. :return: False if the attempt failed due to a missing executable
  1223. or non-zero return code
  1224. :return: True otherwise
  1225. """
  1226. nuldev = open(os.devnull, 'w+')
  1227. try:
  1228. # TODO: the doc or impl is not correct, any return code is accepted
  1229. call([pgm] + list(args), stdin = nuldev, stdout = nuldev, stderr = nuldev)
  1230. found = True
  1231. except:
  1232. found = False
  1233. nuldev.close()
  1234. return found
  1235. # interface to g.mapsets
  1236. def mapsets(search_path=False, env=None):
  1237. """List available mapsets
  1238. :param bool search_path: True to list mapsets only in search path
  1239. :return: list of mapsets
  1240. """
  1241. if search_path:
  1242. flags = 'p'
  1243. else:
  1244. flags = 'l'
  1245. mapsets = read_command('g.mapsets',
  1246. flags=flags,
  1247. sep='newline',
  1248. quiet=True,
  1249. env=env)
  1250. if not mapsets:
  1251. fatal(_("Unable to list mapsets"))
  1252. return mapsets.splitlines()
  1253. # interface to `g.proj -c`
  1254. def create_location(dbase, location, epsg=None, proj4=None, filename=None,
  1255. wkt=None, datum=None, datum_trans=None, desc=None,
  1256. overwrite=False):
  1257. """Create new location
  1258. Raise ScriptError on error.
  1259. :param str dbase: path to GRASS database
  1260. :param str location: location name to create
  1261. :param epsg: if given create new location based on EPSG code
  1262. :param proj4: if given create new location based on Proj4 definition
  1263. :param str filename: if given create new location based on georeferenced file
  1264. :param str wkt: if given create new location based on WKT definition
  1265. (can be path to PRJ file or WKT string)
  1266. :param datum: GRASS format datum code
  1267. :param datum_trans: datum transformation parameters (used for epsg and proj4)
  1268. :param desc: description of the location (creates MYNAME file)
  1269. :param bool overwrite: True to overwrite location if exists(WARNING:
  1270. ALL DATA from existing location ARE DELETED!)
  1271. """
  1272. # create dbase if not exists
  1273. if not os.path.exists(dbase):
  1274. os.mkdir(dbase)
  1275. if epsg or proj4 or filename or wkt:
  1276. # here the location shouldn't really matter
  1277. tmp_gisrc, env = create_environment(dbase, gisenv()['LOCATION_NAME'], 'PERMANENT')
  1278. # check if location already exists
  1279. if os.path.exists(os.path.join(dbase, location)):
  1280. if not overwrite:
  1281. warning(_("Location <%s> already exists. Operation canceled.") % location)
  1282. try_remove(tmp_gisrc)
  1283. return
  1284. else:
  1285. warning(_("Location <%s> already exists and will be overwritten") % location)
  1286. shutil.rmtree(os.path.join(dbase, location))
  1287. stdin = None
  1288. kwargs = dict()
  1289. if datum:
  1290. kwargs['datum'] = datum
  1291. if datum_trans:
  1292. kwargs['datum_trans'] = datum_trans
  1293. if epsg:
  1294. ps = pipe_command('g.proj', quiet=True, flags='t', epsg=epsg,
  1295. location=location, stderr=PIPE, env=env, **kwargs)
  1296. elif proj4:
  1297. ps = pipe_command('g.proj', quiet=True, flags='t', proj4=proj4,
  1298. location=location, stderr=PIPE, env=env, **kwargs)
  1299. elif filename:
  1300. ps = pipe_command('g.proj', quiet=True, georef=filename,
  1301. location=location, stderr=PIPE, env=env)
  1302. elif wkt:
  1303. if os.path.isfile(wkt):
  1304. ps = pipe_command('g.proj', quiet=True, wkt=wkt, location=location,
  1305. stderr=PIPE, env=env)
  1306. else:
  1307. ps = pipe_command('g.proj', quiet=True, wkt='-', location=location,
  1308. stderr=PIPE, stdin=PIPE, env=env)
  1309. stdin = encode(wkt)
  1310. else:
  1311. _create_location_xy(dbase, location)
  1312. if epsg or proj4 or filename or wkt:
  1313. error = ps.communicate(stdin)[1]
  1314. try_remove(tmp_gisrc)
  1315. if ps.returncode != 0 and error:
  1316. raise ScriptError(repr(error))
  1317. try:
  1318. fd = codecs.open(os.path.join(dbase, location, 'PERMANENT', 'MYNAME'),
  1319. encoding='utf-8', mode='w')
  1320. if desc:
  1321. fd.write(desc + os.linesep)
  1322. else:
  1323. fd.write(os.linesep)
  1324. fd.close()
  1325. except OSError as e:
  1326. raise ScriptError(repr(e))
  1327. def _create_location_xy(database, location):
  1328. """Create unprojected location
  1329. Raise ScriptError on error.
  1330. :param database: GRASS database where to create new location
  1331. :param location: location name
  1332. """
  1333. cur_dir = os.getcwd()
  1334. try:
  1335. os.chdir(database)
  1336. os.mkdir(location)
  1337. os.mkdir(os.path.join(location, 'PERMANENT'))
  1338. # create DEFAULT_WIND and WIND files
  1339. regioninfo = ['proj: 0',
  1340. 'zone: 0',
  1341. 'north: 1',
  1342. 'south: 0',
  1343. 'east: 1',
  1344. 'west: 0',
  1345. 'cols: 1',
  1346. 'rows: 1',
  1347. 'e-w resol: 1',
  1348. 'n-s resol: 1',
  1349. 'top: 1',
  1350. 'bottom: 0',
  1351. 'cols3: 1',
  1352. 'rows3: 1',
  1353. 'depths: 1',
  1354. 'e-w resol3: 1',
  1355. 'n-s resol3: 1',
  1356. 't-b resol: 1']
  1357. defwind = open(os.path.join(location,
  1358. "PERMANENT", "DEFAULT_WIND"), 'w')
  1359. for param in regioninfo:
  1360. defwind.write(param + '%s' % os.linesep)
  1361. defwind.close()
  1362. shutil.copy(os.path.join(location, "PERMANENT", "DEFAULT_WIND"),
  1363. os.path.join(location, "PERMANENT", "WIND"))
  1364. os.chdir(cur_dir)
  1365. except OSError as e:
  1366. raise ScriptError(repr(e))
  1367. # interface to g.version
  1368. def version():
  1369. """Get GRASS version as dictionary
  1370. ::
  1371. >>> print(version())
  1372. {'proj4': '4.8.0', 'geos': '3.3.5', 'libgis_revision': '52468',
  1373. 'libgis_date': '2012-07-27 22:53:30 +0200 (Fri, 27 Jul 2012)',
  1374. 'version': '7.0.svn', 'date': '2012', 'gdal': '2.0dev',
  1375. 'revision': '53670'}
  1376. """
  1377. data = parse_command('g.version', flags='rge', errors='ignore')
  1378. for k, v in data.items():
  1379. data[k.strip()] = v.replace('"', '').strip()
  1380. return data
  1381. # get debug_level
  1382. _debug_level = None
  1383. def debug_level(force=False):
  1384. global _debug_level
  1385. if not force and _debug_level is not None:
  1386. return _debug_level
  1387. _debug_level = 0
  1388. if find_program('g.gisenv', '--help'):
  1389. try:
  1390. _debug_level = int(gisenv().get('DEBUG', 0))
  1391. if _debug_level < 0 or _debug_level > 5:
  1392. raise ValueError(_("Debug level {0}").format(_debug_level))
  1393. except ValueError as e:
  1394. _debug_level = 0
  1395. sys.stderr.write(_("WARNING: Ignoring unsupported debug level (must be >=0 and <=5). {0}\n").format(e))
  1396. return _debug_level
  1397. def legal_name(s):
  1398. """Checks if the string contains only allowed characters.
  1399. This is the Python implementation of :func:`G_legal_filename()` function.
  1400. ..note::
  1401. It is not clear when exactly use this function, but it might be
  1402. useful anyway for checking map names and column names.
  1403. """
  1404. if not s or s[0] == '.':
  1405. warning(_("Illegal filename <%s>. Cannot be 'NULL' or start with "
  1406. "'.'.") % s)
  1407. return False
  1408. illegal = [c
  1409. for c in s
  1410. if c in '/"\'@,=*~' or c <= ' ' or c >= '\177']
  1411. if illegal:
  1412. illegal = ''.join(sorted(set(illegal)))
  1413. warning(_("Illegal filename <%(s)s>. <%(il)s> not allowed.\n") % {
  1414. 's': s, 'il': illegal})
  1415. return False
  1416. return True
  1417. def sanitize_mapset_environment(env):
  1418. """Remove environmental variables relevant only
  1419. for a specific mapset. This should be called
  1420. when a copy of environment is used with a different mapset."""
  1421. if "WIND_OVERRIDE" in env:
  1422. del env["WIND_OVERRIDE"]
  1423. if "GRASS_REGION" in env:
  1424. del env["GRASS_REGION"]
  1425. return env
  1426. def create_environment(gisdbase, location, mapset):
  1427. """Creates environment to be passed in run_command for example.
  1428. Returns tuple with temporary file path and the environment. The user
  1429. of this function is responsible for deleting the file."""
  1430. with NamedTemporaryFile(mode='w', delete=False) as f:
  1431. f.write('MAPSET: {mapset}\n'.format(mapset=mapset))
  1432. f.write('GISDBASE: {g}\n'.format(g=gisdbase))
  1433. f.write('LOCATION_NAME: {l}\n'.format(l=location))
  1434. f.write('GUI: text\n')
  1435. env = os.environ.copy()
  1436. env['GISRC'] = f.name
  1437. # remove mapset-specific env vars
  1438. env = sanitize_mapset_environment(env)
  1439. return f.name, env
  1440. if __name__ == '__main__':
  1441. import doctest
  1442. doctest.testmod()