core.py 60 KB

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