core.py 54 KB

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