core.py 52 KB

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