core.py 53 KB

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