core.py 55 KB

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