core.py 49 KB

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