core.py 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009
  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-2020 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. " depreciated in GRASS GIS 7.0 and will be 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. [var, val] = [decode(var), decode(val)]
  715. except:
  716. raise SyntaxError("invalid output from g.parser: %s" % line)
  717. if var.startswith("flag_"):
  718. flags[var[5:]] = bool(int(val))
  719. elif var.startswith("opt_"):
  720. options[var[4:]] = val
  721. elif var in ["GRASS_OVERWRITE", "GRASS_VERBOSE"]:
  722. os.environ[var] = val
  723. else:
  724. raise SyntaxError("invalid output from g.parser: %s" % line)
  725. return (options, flags)
  726. def parser():
  727. """Interface to g.parser, intended to be run from the top-level, e.g.:
  728. ::
  729. if __name__ == "__main__":
  730. options, flags = grass.parser()
  731. main()
  732. Thereafter, the global variables "options" and "flags" will be
  733. dictionaries containing option/flag values, keyed by lower-case
  734. option/flag names. The values in "options" are strings, those in
  735. "flags" are Python booleans.
  736. Overview table of parser standard options:
  737. https://grass.osgeo.org/grass79/manuals/parser_standard_options.html
  738. """
  739. if not os.getenv("GISBASE"):
  740. print("You must be in GRASS GIS to run this program.", file=sys.stderr)
  741. sys.exit(1)
  742. cmdline = [basename(sys.argv[0])]
  743. cmdline += [pipes.quote(a) for a in sys.argv[1:]]
  744. os.environ["CMDLINE"] = " ".join(cmdline)
  745. argv = sys.argv[:]
  746. name = argv[0]
  747. if not os.path.isabs(name):
  748. if os.sep in name or (os.altsep and os.altsep in name):
  749. argv[0] = os.path.abspath(name)
  750. else:
  751. argv[0] = os.path.join(sys.path[0], name)
  752. prog = "g.parser.exe" if sys.platform == "win32" else "g.parser"
  753. p = subprocess.Popen([prog, "-n"] + argv, stdout=subprocess.PIPE)
  754. s = p.communicate()[0]
  755. lines = s.split(b"\0")
  756. if not lines or lines[0] != b"@ARGS_PARSED@":
  757. stdout = os.fdopen(sys.stdout.fileno(), "wb")
  758. stdout.write(s)
  759. sys.exit(p.returncode)
  760. return _parse_opts(lines[1:])
  761. # interface to g.tempfile
  762. def tempfile(create=True, env=None):
  763. """Returns the name of a temporary file, created with g.tempfile.
  764. :param bool create: True to create a file
  765. :param env: environment
  766. :return: path to a tmp file
  767. """
  768. flags = ""
  769. if not create:
  770. flags += "d"
  771. return read_command("g.tempfile", flags=flags, pid=os.getpid(), env=env).strip()
  772. def tempdir(env=None):
  773. """Returns the name of a temporary dir, created with g.tempfile."""
  774. tmp = tempfile(create=False, env=env)
  775. os.mkdir(tmp)
  776. return tmp
  777. def tempname(length, lowercase=False):
  778. """Generate a GRASS and SQL compliant random name starting with tmp_
  779. followed by a random part of length "length"
  780. :param int length: length of the random part of the name to generate
  781. :param bool lowercase: use only lowercase characters to generate name
  782. :returns: String with a random name of length "length" starting with a letter
  783. :rtype: str
  784. :Example:
  785. >>> tempname(12)
  786. 'tmp_MxMa1kAS13s9'
  787. .. seealso:: functions :func:`append_uuid()`, :func:`append_random()`
  788. """
  789. chars = string.ascii_lowercase + string.digits
  790. if not lowercase:
  791. chars += string.ascii_uppercase
  792. random_part = "".join(random.choice(chars) for _ in range(length))
  793. randomname = "tmp_" + random_part
  794. return randomname
  795. def _compare_projection(dic):
  796. """Check if projection has some possibility of duplicate names like
  797. Universal Transverse Mercator and Universe Transverse Mercator and
  798. unify them
  799. :param dic: The dictionary containing information about projection
  800. :return: The dictionary with the new values if needed
  801. """
  802. # the lookup variable is a list of list, each list contains all the
  803. # possible name for a projection system
  804. lookup = [["Universal Transverse Mercator", "Universe Transverse Mercator"]]
  805. for lo in lookup:
  806. for n in range(len(dic["name"])):
  807. if dic["name"][n] in lo:
  808. dic["name"][n] = lo[0]
  809. return dic
  810. def _compare_units(dic):
  811. """Check if units has some possibility of duplicate names like
  812. meter and metre and unify them
  813. :param dic: The dictionary containing information about units
  814. :return: The dictionary with the new values if needed
  815. """
  816. # the lookup variable is a list of list, each list contains all the
  817. # possible name for a units
  818. lookup = [
  819. ["meter", "metre"],
  820. ["meters", "metres"],
  821. ["kilometer", "kilometre"],
  822. ["kilometers", "kilometres"],
  823. ]
  824. for item in lookup:
  825. for n in range(len(dic["unit"])):
  826. if dic["unit"][n].lower() in item:
  827. dic["unit"][n] = item[0]
  828. for n in range(len(dic["units"])):
  829. if dic["units"][n].lower() in item:
  830. dic["units"][n] = item[0]
  831. return dic
  832. def _text_to_key_value_dict(
  833. filename, sep=":", val_sep=",", checkproj=False, checkunits=False
  834. ):
  835. """Convert a key-value text file, where entries are separated by newlines
  836. and the key and value are separated by `sep', into a key-value dictionary
  837. and discover/use the correct data types (float, int or string) for values.
  838. :param str filename: The name or name and path of the text file to convert
  839. :param str sep: The character that separates the keys and values, default
  840. is ":"
  841. :param str val_sep: The character that separates the values of a single
  842. key, default is ","
  843. :param bool checkproj: True if it has to check some information about
  844. projection system
  845. :param bool checkproj: True if it has to check some information about units
  846. :return: The dictionary
  847. A text file with this content:
  848. ::
  849. a: Hello
  850. b: 1.0
  851. c: 1,2,3,4,5
  852. d : hello,8,0.1
  853. Will be represented as this dictionary:
  854. ::
  855. {'a': ['Hello'], 'c': [1, 2, 3, 4, 5], 'b': [1.0], 'd': ['hello', 8, 0.1]}
  856. """
  857. text = open(filename, "r").readlines()
  858. kvdict = KeyValue()
  859. for line in text:
  860. if line.find(sep) >= 0:
  861. key, value = line.split(sep)
  862. key = key.strip()
  863. value = value.strip()
  864. else:
  865. # Jump over empty values
  866. continue
  867. values = value.split(val_sep)
  868. value_list = []
  869. for value in values:
  870. not_float = False
  871. not_int = False
  872. # Convert values into correct types
  873. # We first try integer then float
  874. try:
  875. value_converted = int(value)
  876. except:
  877. not_int = True
  878. if not_int:
  879. try:
  880. value_converted = float(value)
  881. except:
  882. not_float = True
  883. if not_int and not_float:
  884. value_converted = value.strip()
  885. value_list.append(value_converted)
  886. kvdict[key] = value_list
  887. if checkproj:
  888. kvdict = _compare_projection(kvdict)
  889. if checkunits:
  890. kvdict = _compare_units(kvdict)
  891. return kvdict
  892. def compare_key_value_text_files(
  893. filename_a,
  894. filename_b,
  895. sep=":",
  896. val_sep=",",
  897. precision=0.000001,
  898. proj=False,
  899. units=False,
  900. ):
  901. """Compare two key-value text files
  902. This method will print a warning in case keys that are present in the first
  903. file are not present in the second one.
  904. The comparison method tries to convert the values into their native format
  905. (float, int or string) to allow correct comparison.
  906. An example key-value text file may have this content:
  907. ::
  908. a: Hello
  909. b: 1.0
  910. c: 1,2,3,4,5
  911. d : hello,8,0.1
  912. :param str filename_a: name of the first key-value text file
  913. :param str filenmae_b: name of the second key-value text file
  914. :param str sep: character that separates the keys and values, default is ":"
  915. :param str val_sep: character that separates the values of a single key,
  916. default is ","
  917. :param double precision: precision with which the floating point values are compared
  918. :param bool proj: True if it has to check some information about projection system
  919. :param bool units: True if it has to check some information about units
  920. :return: True if full or almost identical, False if different
  921. """
  922. dict_a = _text_to_key_value_dict(filename_a, sep, checkproj=proj, checkunits=units)
  923. dict_b = _text_to_key_value_dict(filename_b, sep, checkproj=proj, checkunits=units)
  924. if sorted(dict_a.keys()) != sorted(dict_b.keys()):
  925. return False
  926. # We compare matching keys
  927. for key in dict_a.keys():
  928. # Floating point values must be handled separately
  929. if isinstance(dict_a[key], float) and isinstance(dict_b[key], float):
  930. if abs(dict_a[key] - dict_b[key]) > precision:
  931. return False
  932. elif isinstance(dict_a[key], float) or isinstance(dict_b[key], float):
  933. warning(
  934. _("Mixing value types. Will try to compare after " "integer conversion")
  935. )
  936. return int(dict_a[key]) == int(dict_b[key])
  937. elif key == "+towgs84":
  938. # We compare the sum of the entries
  939. if abs(sum(dict_a[key]) - sum(dict_b[key])) > precision:
  940. return False
  941. else:
  942. if dict_a[key] != dict_b[key]:
  943. return False
  944. return True
  945. # interface to g.gisenv
  946. def gisenv(env=None):
  947. """Returns the output from running g.gisenv (with no arguments), as a
  948. dictionary. Example:
  949. >>> env = gisenv()
  950. >>> print(env['GISDBASE']) # doctest: +SKIP
  951. /opt/grass-data
  952. :param env run with different environment
  953. :return: list of GRASS variables
  954. """
  955. s = read_command("g.gisenv", flags="n", env=env)
  956. return parse_key_val(s)
  957. # interface to g.region
  958. def locn_is_latlong(env=None):
  959. """Tests if location is lat/long. Value is obtained
  960. by checking the "g.region -pu" projection code.
  961. :return: True for a lat/long region, False otherwise
  962. """
  963. s = read_command("g.region", flags="pu", env=env)
  964. kv = parse_key_val(s, ":")
  965. if kv["projection"].split(" ")[0] == "3":
  966. return True
  967. else:
  968. return False
  969. def region(region3d=False, complete=False, env=None):
  970. """Returns the output from running "g.region -gu", as a
  971. dictionary. Example:
  972. :param bool region3d: True to get 3D region
  973. :param bool complete:
  974. :param env env
  975. >>> curent_region = region()
  976. >>> # obtain n, s, e and w values
  977. >>> [curent_region[key] for key in "nsew"] # doctest: +ELLIPSIS
  978. [..., ..., ..., ...]
  979. >>> # obtain ns and ew resulutions
  980. >>> (curent_region['nsres'], curent_region['ewres']) # doctest: +ELLIPSIS
  981. (..., ...)
  982. :return: dictionary of region values
  983. """
  984. flgs = "gu"
  985. if region3d:
  986. flgs += "3"
  987. if complete:
  988. flgs += "cep"
  989. s = read_command("g.region", flags=flgs, env=env)
  990. reg = parse_key_val(s, val_type=float)
  991. for k in [
  992. "projection",
  993. "zone",
  994. "rows",
  995. "cols",
  996. "cells",
  997. "rows3",
  998. "cols3",
  999. "cells3",
  1000. "depths",
  1001. ]:
  1002. if k not in reg:
  1003. continue
  1004. reg[k] = int(reg[k])
  1005. return reg
  1006. def region_env(region3d=False, flags=None, env=None, **kwargs):
  1007. """Returns region settings as a string which can used as
  1008. GRASS_REGION environmental variable.
  1009. If no 'kwargs' are given then the current region is used. Note
  1010. that this function doesn't modify the current region!
  1011. See also :func:`use_temp_region()` for alternative method how to define
  1012. temporary region used for raster-based computation.
  1013. :param bool region3d: True to get 3D region
  1014. :param string flags: for example 'a'
  1015. :param env: different environment than current
  1016. :param kwargs: g.region's parameters like 'raster', 'vector' or 'region'
  1017. ::
  1018. os.environ['GRASS_REGION'] = grass.region_env(region='detail')
  1019. grass.mapcalc('map=1', overwrite=True)
  1020. os.environ.pop('GRASS_REGION')
  1021. :return: string with region values
  1022. :return: empty string on error
  1023. """
  1024. # read proj/zone from WIND file
  1025. gis_env = gisenv(env)
  1026. windfile = os.path.join(
  1027. gis_env["GISDBASE"], gis_env["LOCATION_NAME"], gis_env["MAPSET"], "WIND"
  1028. )
  1029. with open(windfile, "r") as fd:
  1030. grass_region = ""
  1031. for line in fd.readlines():
  1032. key, value = map(lambda x: x.strip(), line.split(":", 1))
  1033. if kwargs and key not in ("proj", "zone"):
  1034. continue
  1035. if (
  1036. not kwargs
  1037. and not region3d
  1038. and key
  1039. in (
  1040. "top",
  1041. "bottom",
  1042. "cols3",
  1043. "rows3",
  1044. "depths",
  1045. "e-w resol3",
  1046. "n-s resol3",
  1047. "t-b resol",
  1048. )
  1049. ):
  1050. continue
  1051. grass_region += "%s: %s;" % (key, value)
  1052. if not kwargs: # return current region
  1053. return grass_region
  1054. # read other values from `g.region -gu`
  1055. flgs = "ug"
  1056. if region3d:
  1057. flgs += "3"
  1058. if flags:
  1059. flgs += flags
  1060. s = read_command("g.region", flags=flgs, env=env, **kwargs)
  1061. if not s:
  1062. return ""
  1063. reg = parse_key_val(s)
  1064. kwdata = [
  1065. ("north", "n"),
  1066. ("south", "s"),
  1067. ("east", "e"),
  1068. ("west", "w"),
  1069. ("cols", "cols"),
  1070. ("rows", "rows"),
  1071. ("e-w resol", "ewres"),
  1072. ("n-s resol", "nsres"),
  1073. ]
  1074. if region3d:
  1075. kwdata += [
  1076. ("top", "t"),
  1077. ("bottom", "b"),
  1078. ("cols3", "cols3"),
  1079. ("rows3", "rows3"),
  1080. ("depths", "depths"),
  1081. ("e-w resol3", "ewres3"),
  1082. ("n-s resol3", "nsres3"),
  1083. ("t-b resol", "tbres"),
  1084. ]
  1085. for wkey, rkey in kwdata:
  1086. grass_region += "%s: %s;" % (wkey, reg[rkey])
  1087. return grass_region
  1088. def use_temp_region():
  1089. """Copies the current region to a temporary region with "g.region save=",
  1090. then sets WIND_OVERRIDE to refer to that region. Installs an atexit
  1091. handler to delete the temporary region upon termination.
  1092. """
  1093. name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
  1094. run_command("g.region", flags="u", save=name, overwrite=True)
  1095. os.environ["WIND_OVERRIDE"] = name
  1096. atexit.register(del_temp_region)
  1097. def del_temp_region():
  1098. """Unsets WIND_OVERRIDE and removes any region named by it."""
  1099. try:
  1100. name = os.environ.pop("WIND_OVERRIDE")
  1101. run_command("g.remove", flags="f", quiet=True, type="region", name=name)
  1102. except:
  1103. pass
  1104. # interface to g.findfile
  1105. def find_file(name, element="cell", mapset=None, env=None):
  1106. """Returns the output from running g.findfile as a
  1107. dictionary. Example:
  1108. >>> result = find_file('elevation', element='cell')
  1109. >>> print(result['fullname'])
  1110. elevation@PERMANENT
  1111. >>> print(result['file']) # doctest: +ELLIPSIS
  1112. /.../PERMANENT/cell/elevation
  1113. :param str name: file name
  1114. :param str element: element type (default 'cell')
  1115. :param str mapset: mapset name (default all mapsets in search path)
  1116. :param env: environment
  1117. :return: parsed output of g.findfile
  1118. """
  1119. if element == "raster" or element == "rast":
  1120. verbose(_('Element type should be "cell" and not "%s"') % element)
  1121. element = "cell"
  1122. # g.findfile returns non-zero when file was not found
  1123. # se we ignore return code and just focus on stdout
  1124. process = start_command(
  1125. "g.findfile",
  1126. flags="n",
  1127. element=element,
  1128. file=name,
  1129. mapset=mapset,
  1130. stdout=PIPE,
  1131. env=env,
  1132. )
  1133. stdout = process.communicate()[0]
  1134. return parse_key_val(stdout)
  1135. # interface to g.list
  1136. def list_strings(type, pattern=None, mapset=None, exclude=None, flag="", env=None):
  1137. """List of elements as strings.
  1138. Returns the output from running g.list, as a list of qualified
  1139. names.
  1140. :param str type: element type (raster, vector, raster_3d, region, ...)
  1141. :param str pattern: pattern string
  1142. :param str mapset: mapset name (if not given use search path)
  1143. :param str exclude: pattern string to exclude maps from the research
  1144. :param str flag: pattern type: 'r' (basic regexp), 'e' (extended regexp),
  1145. or '' (glob pattern)
  1146. :param env: environment
  1147. :return: list of elements
  1148. """
  1149. if type == "cell":
  1150. verbose(_('Element type should be "raster" and not "%s"') % type)
  1151. result = list()
  1152. for line in read_command(
  1153. "g.list",
  1154. quiet=True,
  1155. flags="m" + flag,
  1156. type=type,
  1157. pattern=pattern,
  1158. exclude=exclude,
  1159. mapset=mapset,
  1160. env=env,
  1161. ).splitlines():
  1162. result.append(line.strip())
  1163. return result
  1164. def list_pairs(type, pattern=None, mapset=None, exclude=None, flag="", env=None):
  1165. """List of elements as pairs
  1166. Returns the output from running g.list, as a list of
  1167. (name, mapset) pairs
  1168. :param str type: element type (raster, vector, raster_3d, region, ...)
  1169. :param str pattern: pattern string
  1170. :param str mapset: mapset name (if not given use search path)
  1171. :param str exclude: pattern string to exclude maps from the research
  1172. :param str flag: pattern type: 'r' (basic regexp), 'e' (extended regexp),
  1173. or '' (glob pattern)
  1174. :param env: environment
  1175. :return: list of elements
  1176. """
  1177. return [
  1178. tuple(map.split("@", 1))
  1179. for map in list_strings(type, pattern, mapset, exclude, flag, env)
  1180. ]
  1181. def list_grouped(
  1182. type, pattern=None, check_search_path=True, exclude=None, flag="", env=None
  1183. ):
  1184. """List of elements grouped by mapsets.
  1185. Returns the output from running g.list, as a dictionary where the
  1186. keys are mapset names and the values are lists of maps in that
  1187. mapset. Example:
  1188. >>> list_grouped('vect', pattern='*roads*')['PERMANENT']
  1189. ['railroads', 'roadsmajor']
  1190. :param str type: element type (raster, vector, raster_3d, region, ...)
  1191. or list of elements
  1192. :param str pattern: pattern string
  1193. :param str check_search_path: True to add mapsets for the search path
  1194. with no found elements
  1195. :param str exclude: pattern string to exclude maps from the research
  1196. :param str flag: pattern type: 'r' (basic regexp), 'e' (extended regexp),
  1197. or '' (glob pattern)
  1198. :param env: environment
  1199. :return: directory of mapsets/elements
  1200. """
  1201. if isinstance(type, str) or len(type) == 1:
  1202. types = [type]
  1203. store_types = False
  1204. else:
  1205. types = type
  1206. store_types = True
  1207. flag += "t"
  1208. for i in range(len(types)):
  1209. if types[i] == "cell":
  1210. verbose(_('Element type should be "raster" and not "%s"') % types[i])
  1211. types[i] = "raster"
  1212. result = {}
  1213. if check_search_path:
  1214. for mapset in mapsets(search_path=True, env=env):
  1215. if store_types:
  1216. result[mapset] = {}
  1217. else:
  1218. result[mapset] = []
  1219. mapset = None
  1220. for line in read_command(
  1221. "g.list",
  1222. quiet=True,
  1223. flags="m" + flag,
  1224. type=types,
  1225. pattern=pattern,
  1226. exclude=exclude,
  1227. env=env,
  1228. ).splitlines():
  1229. try:
  1230. name, mapset = line.split("@")
  1231. except ValueError:
  1232. warning(_("Invalid element '%s'") % line)
  1233. continue
  1234. if store_types:
  1235. type_, name = name.split("/")
  1236. if mapset in result:
  1237. if type_ in result[mapset]:
  1238. result[mapset][type_].append(name)
  1239. else:
  1240. result[mapset][type_] = [
  1241. name,
  1242. ]
  1243. else:
  1244. result[mapset] = {
  1245. type_: [
  1246. name,
  1247. ]
  1248. }
  1249. else:
  1250. if mapset in result:
  1251. result[mapset].append(name)
  1252. else:
  1253. result[mapset] = [
  1254. name,
  1255. ]
  1256. return result
  1257. # color parsing
  1258. named_colors = {
  1259. "white": (1.00, 1.00, 1.00),
  1260. "black": (0.00, 0.00, 0.00),
  1261. "red": (1.00, 0.00, 0.00),
  1262. "green": (0.00, 1.00, 0.00),
  1263. "blue": (0.00, 0.00, 1.00),
  1264. "yellow": (1.00, 1.00, 0.00),
  1265. "magenta": (1.00, 0.00, 1.00),
  1266. "cyan": (0.00, 1.00, 1.00),
  1267. "aqua": (0.00, 0.75, 0.75),
  1268. "grey": (0.75, 0.75, 0.75),
  1269. "gray": (0.75, 0.75, 0.75),
  1270. "orange": (1.00, 0.50, 0.00),
  1271. "brown": (0.75, 0.50, 0.25),
  1272. "purple": (0.50, 0.00, 1.00),
  1273. "violet": (0.50, 0.00, 1.00),
  1274. "indigo": (0.00, 0.50, 1.00),
  1275. }
  1276. def parse_color(val, dflt=None):
  1277. """Parses the string "val" as a GRASS colour, which can be either one of
  1278. the named colours or an R:G:B tuple e.g. 255:255:255. Returns an
  1279. (r,g,b) triple whose components are floating point values between 0
  1280. and 1. Example:
  1281. >>> parse_color("red")
  1282. (1.0, 0.0, 0.0)
  1283. >>> parse_color("255:0:0")
  1284. (1.0, 0.0, 0.0)
  1285. :param val: color value
  1286. :param dflt: default color value
  1287. :return: tuple RGB
  1288. """
  1289. if val in named_colors:
  1290. return named_colors[val]
  1291. vals = val.split(":")
  1292. if len(vals) == 3:
  1293. return tuple(float(v) / 255 for v in vals)
  1294. return dflt
  1295. # check GRASS_OVERWRITE
  1296. def overwrite():
  1297. """Return True if existing files may be overwritten"""
  1298. owstr = "GRASS_OVERWRITE"
  1299. return owstr in os.environ and os.environ[owstr] != "0"
  1300. # check GRASS_VERBOSE
  1301. def verbosity():
  1302. """Return the verbosity level selected by GRASS_VERBOSE
  1303. Currently, there are 5 levels of verbosity:
  1304. -1 nothing will be printed (also fatal errors and warnings will be discarded)
  1305. 0 only errors and warnings are printed, triggered by "--q" or "--quiet" flag.
  1306. 1 progress information (percent) and important messages will be printed
  1307. 2 all messages will be printed
  1308. 3 also verbose messages will be printed. Triggered by "--v" or "--verbose" flag.
  1309. """
  1310. vbstr = os.getenv("GRASS_VERBOSE")
  1311. if vbstr:
  1312. return int(vbstr)
  1313. else:
  1314. return 2
  1315. # Various utilities, not specific to GRASS
  1316. def find_program(pgm, *args):
  1317. """Attempt to run a program, with optional arguments.
  1318. You must call the program in a way that will return a successful
  1319. exit code. For GRASS modules this means you need to pass it some
  1320. valid CLI option, like "--help". For other programs a common
  1321. valid do-little option is usually "--version".
  1322. Example:
  1323. >>> find_program('r.sun', '--help')
  1324. True
  1325. >>> find_program('ls', '--version')
  1326. True
  1327. :param str pgm: program name
  1328. :param args: list of arguments
  1329. :return: False if the attempt failed due to a missing executable
  1330. or non-zero return code
  1331. :return: True otherwise
  1332. """
  1333. nuldev = open(os.devnull, "w+")
  1334. try:
  1335. # TODO: the doc or impl is not correct, any return code is accepted
  1336. call([pgm] + list(args), stdin=nuldev, stdout=nuldev, stderr=nuldev)
  1337. found = True
  1338. except:
  1339. found = False
  1340. nuldev.close()
  1341. return found
  1342. # interface to g.mapsets
  1343. def mapsets(search_path=False, env=None):
  1344. """List available mapsets
  1345. :param bool search_path: True to list mapsets only in search path
  1346. :return: list of mapsets
  1347. """
  1348. if search_path:
  1349. flags = "p"
  1350. else:
  1351. flags = "l"
  1352. mapsets = read_command("g.mapsets", flags=flags, sep="newline", quiet=True, env=env)
  1353. if not mapsets:
  1354. fatal(_("Unable to list mapsets"))
  1355. return mapsets.splitlines()
  1356. # interface to `g.proj -c`
  1357. def create_location(
  1358. dbase,
  1359. location,
  1360. epsg=None,
  1361. proj4=None,
  1362. filename=None,
  1363. wkt=None,
  1364. datum=None,
  1365. datum_trans=None,
  1366. desc=None,
  1367. overwrite=False,
  1368. ):
  1369. """Create new location
  1370. Raise ScriptError on error.
  1371. :param str dbase: path to GRASS database
  1372. :param str location: location name to create
  1373. :param epsg: if given create new location based on EPSG code
  1374. :param proj4: if given create new location based on Proj4 definition
  1375. :param str filename: if given create new location based on georeferenced file
  1376. :param str wkt: if given create new location based on WKT definition
  1377. (can be path to PRJ file or WKT string)
  1378. :param datum: GRASS format datum code
  1379. :param datum_trans: datum transformation parameters (used for epsg and proj4)
  1380. :param desc: description of the location (creates MYNAME file)
  1381. :param bool overwrite: True to overwrite location if exists(WARNING:
  1382. ALL DATA from existing location ARE DELETED!)
  1383. """
  1384. # create dbase if not exists
  1385. if not os.path.exists(dbase):
  1386. os.mkdir(dbase)
  1387. if epsg or proj4 or filename or wkt:
  1388. # here the location shouldn't really matter
  1389. tmp_gisrc, env = create_environment(
  1390. dbase, gisenv()["LOCATION_NAME"], "PERMANENT"
  1391. )
  1392. # check if location already exists
  1393. if os.path.exists(os.path.join(dbase, location)):
  1394. if not overwrite:
  1395. warning(_("Location <%s> already exists. Operation canceled.") % location)
  1396. try_remove(tmp_gisrc)
  1397. return
  1398. else:
  1399. warning(
  1400. _("Location <%s> already exists and will be overwritten") % location
  1401. )
  1402. shutil.rmtree(os.path.join(dbase, location))
  1403. stdin = None
  1404. kwargs = dict()
  1405. if datum:
  1406. kwargs["datum"] = datum
  1407. if datum_trans:
  1408. kwargs["datum_trans"] = datum_trans
  1409. if epsg:
  1410. ps = pipe_command(
  1411. "g.proj",
  1412. quiet=True,
  1413. flags="t",
  1414. epsg=epsg,
  1415. location=location,
  1416. stderr=PIPE,
  1417. env=env,
  1418. **kwargs,
  1419. )
  1420. elif proj4:
  1421. ps = pipe_command(
  1422. "g.proj",
  1423. quiet=True,
  1424. flags="t",
  1425. proj4=proj4,
  1426. location=location,
  1427. stderr=PIPE,
  1428. env=env,
  1429. **kwargs,
  1430. )
  1431. elif filename:
  1432. ps = pipe_command(
  1433. "g.proj",
  1434. quiet=True,
  1435. georef=filename,
  1436. location=location,
  1437. stderr=PIPE,
  1438. env=env,
  1439. )
  1440. elif wkt:
  1441. if os.path.isfile(wkt):
  1442. ps = pipe_command(
  1443. "g.proj", quiet=True, wkt=wkt, location=location, stderr=PIPE, env=env
  1444. )
  1445. else:
  1446. ps = pipe_command(
  1447. "g.proj",
  1448. quiet=True,
  1449. wkt="-",
  1450. location=location,
  1451. stderr=PIPE,
  1452. stdin=PIPE,
  1453. env=env,
  1454. )
  1455. stdin = encode(wkt)
  1456. else:
  1457. _create_location_xy(dbase, location)
  1458. if epsg or proj4 or filename or wkt:
  1459. error = ps.communicate(stdin)[1]
  1460. try_remove(tmp_gisrc)
  1461. if ps.returncode != 0 and error:
  1462. raise ScriptError(repr(error))
  1463. try:
  1464. fd = codecs.open(
  1465. os.path.join(dbase, location, "PERMANENT", "MYNAME"),
  1466. encoding="utf-8",
  1467. mode="w",
  1468. )
  1469. if desc:
  1470. fd.write(desc + os.linesep)
  1471. else:
  1472. fd.write(os.linesep)
  1473. fd.close()
  1474. except OSError as e:
  1475. raise ScriptError(repr(e))
  1476. def _create_location_xy(database, location):
  1477. """Create unprojected location
  1478. Raise ScriptError on error.
  1479. :param database: GRASS database where to create new location
  1480. :param location: location name
  1481. """
  1482. cur_dir = os.getcwd()
  1483. try:
  1484. os.chdir(database)
  1485. os.mkdir(location)
  1486. os.mkdir(os.path.join(location, "PERMANENT"))
  1487. # create DEFAULT_WIND and WIND files
  1488. regioninfo = [
  1489. "proj: 0",
  1490. "zone: 0",
  1491. "north: 1",
  1492. "south: 0",
  1493. "east: 1",
  1494. "west: 0",
  1495. "cols: 1",
  1496. "rows: 1",
  1497. "e-w resol: 1",
  1498. "n-s resol: 1",
  1499. "top: 1",
  1500. "bottom: 0",
  1501. "cols3: 1",
  1502. "rows3: 1",
  1503. "depths: 1",
  1504. "e-w resol3: 1",
  1505. "n-s resol3: 1",
  1506. "t-b resol: 1",
  1507. ]
  1508. defwind = open(os.path.join(location, "PERMANENT", "DEFAULT_WIND"), "w")
  1509. for param in regioninfo:
  1510. defwind.write(param + "%s" % os.linesep)
  1511. defwind.close()
  1512. shutil.copy(
  1513. os.path.join(location, "PERMANENT", "DEFAULT_WIND"),
  1514. os.path.join(location, "PERMANENT", "WIND"),
  1515. )
  1516. os.chdir(cur_dir)
  1517. except OSError as e:
  1518. raise ScriptError(repr(e))
  1519. # interface to g.version
  1520. def version():
  1521. """Get GRASS version as dictionary
  1522. ::
  1523. >>> print(version())
  1524. {'proj4': '4.8.0', 'geos': '3.3.5', 'libgis_revision': '52468',
  1525. 'libgis_date': '2012-07-27 22:53:30 +0200 (Fri, 27 Jul 2012)',
  1526. 'version': '7.0.svn', 'date': '2012', 'gdal': '2.0dev',
  1527. 'revision': '53670'}
  1528. """
  1529. data = parse_command("g.version", flags="rge", errors="ignore")
  1530. for k, v in data.items():
  1531. data[k.strip()] = v.replace('"', "").strip()
  1532. return data
  1533. # get debug_level
  1534. _debug_level = None
  1535. def debug_level(force=False):
  1536. global _debug_level
  1537. if not force and _debug_level is not None:
  1538. return _debug_level
  1539. _debug_level = 0
  1540. if find_program("g.gisenv", "--help"):
  1541. try:
  1542. _debug_level = int(gisenv().get("DEBUG", 0))
  1543. if _debug_level < 0 or _debug_level > 5:
  1544. raise ValueError(_("Debug level {0}").format(_debug_level))
  1545. except ValueError as e:
  1546. _debug_level = 0
  1547. sys.stderr.write(
  1548. _(
  1549. "WARNING: Ignoring unsupported debug level (must be >=0 and <=5):"
  1550. " {}\n"
  1551. ).format(e)
  1552. )
  1553. return _debug_level
  1554. # TODO: Move legal_name() to utils or a new dedicated "name" module.
  1555. # TODO: Remove the pygrass backwards compatibility version of it?
  1556. def legal_name(s):
  1557. """Checks if the string contains only allowed characters.
  1558. This is the Python implementation of :func:`G_legal_filename()` function.
  1559. ..note::
  1560. It is not clear when exactly use this function, but it might be
  1561. useful anyway for checking map names and column names.
  1562. """
  1563. if not s or s[0] == ".":
  1564. warning(_("Illegal filename <%s>. Cannot be 'NULL' or start with " "'.'.") % s)
  1565. return False
  1566. illegal = [c for c in s if c in "/\"'@,=*~" or c <= " " or c >= "\177"]
  1567. if illegal:
  1568. illegal = "".join(sorted(set(illegal)))
  1569. warning(
  1570. _("Illegal filename <%(s)s>. <%(il)s> not allowed.\n")
  1571. % {"s": s, "il": illegal}
  1572. )
  1573. return False
  1574. return True
  1575. def sanitize_mapset_environment(env):
  1576. """Remove environmental variables relevant only
  1577. for a specific mapset. This should be called
  1578. when a copy of environment is used with a different mapset."""
  1579. if "WIND_OVERRIDE" in env:
  1580. del env["WIND_OVERRIDE"]
  1581. if "GRASS_REGION" in env:
  1582. del env["GRASS_REGION"]
  1583. return env
  1584. def create_environment(gisdbase, location, mapset):
  1585. """Creates environment to be passed in run_command for example.
  1586. Returns tuple with temporary file path and the environment. The user
  1587. of this function is responsible for deleting the file."""
  1588. with NamedTemporaryFile(mode="w", delete=False) as f:
  1589. f.write("MAPSET: {mapset}\n".format(mapset=mapset))
  1590. f.write("GISDBASE: {g}\n".format(g=gisdbase))
  1591. f.write("LOCATION_NAME: {l}\n".format(l=location))
  1592. f.write("GUI: text\n")
  1593. env = os.environ.copy()
  1594. env["GISRC"] = f.name
  1595. # remove mapset-specific env vars
  1596. env = sanitize_mapset_environment(env)
  1597. return f.name, env
  1598. if __name__ == "__main__":
  1599. import doctest
  1600. doctest.testmod()