core.py 54 KB

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