core.py 55 KB

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