core.py 54 KB

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