core.py 52 KB

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