core.py 60 KB

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