core.py 49 KB

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