core.py 54 KB

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