core.py 48 KB

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