core.py 57 KB

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