core.py 58 KB

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