GRASS Programmer's Manual  6.4.2(2012)
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
core.py
Go to the documentation of this file.
1 """!@package grass.script.core
2 
3 @brief GRASS Python scripting module (core functions)
4 
5 Core functions to be used in Python scripts.
6 
7 Usage:
8 
9 @code
10 from grass.script import core as grass
11 
12 grass.parser()
13 ...
14 @endcode
15 
16 (C) 2008-2011 by the GRASS Development Team
17 This program is free software under the GNU General Public
18 License (>=v2). Read the file COPYING that comes with GRASS
19 for details.
20 
21 @author Glynn Clements
22 @author Martin Landa <landa.martin gmail.com>
23 @author Michael Barton <michael.barton asu.edu>
24 """
25 
26 import os
27 import sys
28 import types
29 import re
30 import atexit
31 import subprocess
32 import shutil
33 import locale
34 import codecs
35 
36 # i18N
37 import gettext
38 gettext.install('grasslibs', os.path.join(os.getenv("GISBASE"), 'locale'), unicode=True)
39 
40 # subprocess wrapper that uses shell on Windows
41 
42 class Popen(subprocess.Popen):
43  def __init__(self, args, bufsize = 0, executable = None,
44  stdin = None, stdout = None, stderr = None,
45  preexec_fn = None, close_fds = False, shell = None,
46  cwd = None, env = None, universal_newlines = False,
47  startupinfo = None, creationflags = 0):
48 
49  if shell == None:
50  shell = (sys.platform == "win32")
51 
52  subprocess.Popen.__init__(self, args, bufsize, executable,
53  stdin, stdout, stderr,
54  preexec_fn, close_fds, shell,
55  cwd, env, universal_newlines,
56  startupinfo, creationflags)
57 
58 PIPE = subprocess.PIPE
59 STDOUT = subprocess.STDOUT
60 
61 class ScriptError(Exception):
62  def __init__(self, msg):
63  self.value = msg
64 
65  def __str__(self):
66  return repr(self.value)
67 
68 raise_on_error = False # raise exception instead of calling fatal()
69 debug_level = 0 # DEBUG level
70 
71 def call(*args, **kwargs):
72  return Popen(*args, **kwargs).wait()
73 
74 # GRASS-oriented interface to subprocess module
75 
76 _popen_args = ["bufsize", "executable", "stdin", "stdout", "stderr",
77  "preexec_fn", "close_fds", "cwd", "env",
78  "universal_newlines", "startupinfo", "creationflags"]
79 
80 def decode(string):
81  enc = locale.getdefaultlocale()[1]
82  if enc:
83  return string.decode(enc)
84 
85  return string
86 
87 def _make_val(val):
88  if isinstance(val, types.StringType) or \
89  isinstance(val, types.UnicodeType):
90  return val
91  if isinstance(val, types.ListType):
92  return ",".join(map(_make_val, val))
93  if isinstance(val, types.TupleType):
94  return _make_val(list(val))
95  return str(val)
96 
97 def make_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, **options):
98  """!Return a list of strings suitable for use as the args parameter to
99  Popen() or call(). Example:
100 
101  @code
102  >>> grass.make_command("g.message", flags = 'w', message = 'this is a warning')
103  ['g.message', '-w', 'message=this is a warning']
104  @endcode
105 
106  @param prog GRASS module
107  @param flags flags to be used (given as a string)
108  @param overwrite True to enable overwriting the output (<tt>--o</tt>)
109  @param quiet True to run quietly (<tt>--q</tt>)
110  @param verbose True to run verbosely (<tt>--v</tt>)
111  @param options module's parameters
112 
113  @return list of arguments
114  """
115  args = [prog]
116  if overwrite:
117  args.append("--o")
118  if quiet:
119  args.append("--q")
120  if verbose:
121  args.append("--v")
122  if flags:
123  if '-' in flags:
124  raise ScriptError("'-' is not a valid flag")
125  args.append("-%s" % flags)
126  for opt, val in options.iteritems():
127  if val != None:
128  if opt[0] == '_':
129  opt = opt[1:]
130  args.append("%s=%s" % (opt, _make_val(val)))
131  return args
132 
133 def start_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, **kwargs):
134  """!Returns a Popen object with the command created by make_command.
135  Accepts any of the arguments which Popen() accepts apart from "args"
136  and "shell".
137 
138  \code
139  >>> p = grass.start_command("g.gisenv", stdout = subprocess.PIPE)
140  >>> print p
141  <subprocess.Popen object at 0xb7c12f6c>
142  >>> print p.communicate()[0]
143  GISDBASE='/opt/grass-data';
144  LOCATION_NAME='spearfish60';
145  MAPSET='glynn';
146  GRASS_DB_ENCODING='ascii';
147  GRASS_GUI='text';
148  MONITOR='x0';
149  \endcode
150 
151  @param prog GRASS module
152  @param flags flags to be used (given as a string)
153  @param overwrite True to enable overwriting the output (<tt>--o</tt>)
154  @param quiet True to run quietly (<tt>--q</tt>)
155  @param verbose True to run verbosely (<tt>--v</tt>)
156  @param kwargs module's parameters
157 
158  @return Popen object
159  """
160  options = {}
161  popts = {}
162  for opt, val in kwargs.iteritems():
163  if opt in _popen_args:
164  popts[opt] = val
165  else:
166  options[opt] = val
167  args = make_command(prog, flags, overwrite, quiet, verbose, **options)
168  if sys.platform == 'win32' and os.path.splitext(prog)[1] == '.py':
169  os.chdir(os.path.join(os.getenv('GISBASE'), 'etc', 'gui', 'scripts'))
170  args.insert(0, sys.executable)
171 
172  global debug_level
173  if debug_level > 0:
174  sys.stderr.write("D1/%d: %s.start_command(): %s\n" % (debug_level, __name__, ' '.join(args)))
175  sys.stderr.flush()
176 
177  return Popen(args, **popts)
178 
179 def run_command(*args, **kwargs):
180  """!Passes all arguments to start_command(), then waits for the process to
181  complete, returning its exit code. Similar to subprocess.call(), but
182  with the make_command() interface.
183 
184  @param args list of unnamed arguments (see start_command() for details)
185  @param kwargs list of named arguments (see start_command() for details)
186 
187  @return exit code (0 for success)
188  """
189  ps = start_command(*args, **kwargs)
190  return ps.wait()
191 
192 def pipe_command(*args, **kwargs):
193  """!Passes all arguments to start_command(), but also adds
194  "stdout = PIPE". Returns the Popen object.
195 
196  \code
197  >>> p = grass.pipe_command("g.gisenv")
198  >>> print p
199  <subprocess.Popen object at 0xb7c12f6c>
200  >>> print p.communicate()[0]
201  GISDBASE='/opt/grass-data';
202  LOCATION_NAME='spearfish60';
203  MAPSET='glynn';
204  GRASS_DB_ENCODING='ascii';
205  GRASS_GUI='text';
206  MONITOR='x0';
207  \endcode
208 
209  @param args list of unnamed arguments (see start_command() for details)
210  @param kwargs list of named arguments (see start_command() for details)
211 
212  @return Popen object
213  """
214  kwargs['stdout'] = PIPE
215  return start_command(*args, **kwargs)
216 
217 def feed_command(*args, **kwargs):
218  """!Passes all arguments to start_command(), but also adds
219  "stdin = PIPE". Returns the Popen object.
220 
221  @param args list of unnamed arguments (see start_command() for details)
222  @param kwargs list of named arguments (see start_command() for details)
223 
224  @return Popen object
225  """
226  kwargs['stdin'] = PIPE
227  return start_command(*args, **kwargs)
228 
229 def read_command(*args, **kwargs):
230  """!Passes all arguments to pipe_command, then waits for the process to
231  complete, returning its stdout (i.e. similar to shell `backticks`).
232 
233  @param args list of unnamed arguments (see start_command() for details)
234  @param kwargs list of named arguments (see start_command() for details)
235 
236  @return stdout
237  """
238  ps = pipe_command(*args, **kwargs)
239  return ps.communicate()[0]
240 
241 def parse_command(*args, **kwargs):
242  """!Passes all arguments to read_command, then parses the output
243  by parse_key_val().
244 
245  Parsing function can be optionally given by <em>parse</em> parameter
246  including its arguments, e.g.
247 
248  @code
249  parse_command(..., parse = (grass.parse_key_val, { 'sep' : ':' }))
250  @endcode
251 
252  or you can simply define <em>delimiter</em>
253 
254  @code
255  parse_command(..., delimiter = ':')
256  @endcode
257 
258  @param args list of unnamed arguments (see start_command() for details)
259  @param kwargs list of named arguments (see start_command() for details)
260 
261  @return parsed module output
262  """
263  parse = None
264  parse_args = {}
265  if 'parse' in kwargs:
266  if type(kwargs['parse']) is types.TupleType:
267  parse = kwargs['parse'][0]
268  parse_args = kwargs['parse'][1]
269  del kwargs['parse']
270 
271  if 'delimiter' in kwargs:
272  parse_args = { 'sep' : kwargs['delimiter'] }
273  del kwargs['delimiter']
274 
275  if not parse:
276  parse = parse_key_val # use default fn
277 
278  res = read_command(*args, **kwargs)
279 
280  return parse(res, **parse_args)
281 
282 def write_command(*args, **kwargs):
283  """!Passes all arguments to feed_command, with the string specified
284  by the 'stdin' argument fed to the process' stdin.
285 
286  @param args list of unnamed arguments (see start_command() for details)
287  @param kwargs list of named arguments (see start_command() for details)
288 
289  @return return code
290  """
291  stdin = kwargs['stdin']
292  p = feed_command(*args, **kwargs)
293  p.stdin.write(stdin)
294  p.stdin.close()
295  return p.wait()
296 
297 def exec_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, env = None, **kwargs):
298  """!Interface to os.execvpe(), but with the make_command() interface.
299 
300  @param prog GRASS module
301  @param flags flags to be used (given as a string)
302  @param overwrite True to enable overwriting the output (<tt>--o</tt>)
303  @param quiet True to run quietly (<tt>--q</tt>)
304  @param verbose True to run verbosely (<tt>--v</tt>)
305  @param env directory with enviromental variables
306  @param kwargs module's parameters
307 
308  """
309  args = make_command(prog, flags, overwrite, quiet, verbose, **kwargs)
310  if env == None:
311  env = os.environ
312  os.execvpe(prog, args, env)
313 
314 # interface to g.message
315 
316 def message(msg, flag = None):
317  """!Display a message using `g.message`
318 
319  @param msg message to be displayed
320  @param flag flags (given as string)
321  """
322  run_command("g.message", flags = flag, message = msg)
323 
324 def debug(msg, debug = 1):
325  """!Display a debugging message using `g.message -d`
326 
327  @param msg debugging message to be displayed
328  @param debug debug level (0-5)
329  """
330  run_command("g.message", flags = 'd', message = msg, debug = debug)
331 
332 def verbose(msg):
333  """!Display a verbose message using `g.message -v`
334 
335  @param msg verbose message to be displayed
336  """
337  message(msg, flag = 'v')
338 
339 def info(msg):
340  """!Display an informational message using `g.message -i`
341 
342  @param msg informational message to be displayed
343  """
344  message(msg, flag = 'i')
345 
346 def percent(i, n, s):
347  """!Display a progress info message using `g.message -p`
348 
349  @code
350  message(_("Percent complete..."))
351  n = 100
352  for i in range(n):
353  percent(i, n, 1)
354  percent(1, 1, 1)
355  @endcode
356 
357  @param i current item
358  @param n total number of items
359  @param s increment size
360  """
361  message("%d %d %d" % (i, n, s), flag = 'p')
362 
363 def warning(msg):
364  """!Display a warning message using `g.message -w`
365 
366  @param msg warning message to be displayed
367  """
368  message(msg, flag = 'w')
369 
370 def error(msg):
371  """!Display an error message using `g.message -e`
372 
373  Raise exception when on_error is 'raise'.
374 
375  @param msg error message to be displayed
376  """
377  global raise_on_error
378  if raise_on_error:
379  raise ScriptError(msg)
380  else:
381  message(msg, flag = 'e')
382 
383 def fatal(msg):
384  """!Display an error message using `g.message -e`, then abort
385 
386  @param msg error message to be displayed
387  """
388  error(msg)
389  sys.exit(1)
390 
391 def set_raise_on_error(raise_exp = True):
392  """!Define behaviour on error (error() called)
393 
394  @param raise_exp True to raise ScriptError instead of calling
395  error()
396 
397  @return current status
398  """
399  global raise_on_error
400  tmp_raise = raise_on_error
401  raise_on_error = raise_exp
402 
403 # interface to g.parser
404 
405 def _parse_opts(lines):
406  options = {}
407  flags = {}
408  for line in lines:
409  line = line.rstrip('\r\n')
410  if not line:
411  break
412  try:
413  [var, val] = line.split('=', 1)
414  except:
415  raise SyntaxError("invalid output from g.parser: %s" % line)
416 
417  if var.startswith('flag_'):
418  flags[var[5:]] = bool(int(val))
419  elif var.startswith('opt_'):
420  options[var[4:]] = val
421  elif var in ['GRASS_OVERWRITE', 'GRASS_VERBOSE']:
422  os.environ[var] = val
423  else:
424  raise SyntaxError("invalid output from g.parser: %s" % line)
425 
426  return (options, flags)
427 
428 def parser():
429  """!Interface to g.parser, intended to be run from the top-level, e.g.:
430 
431  @code
432  if __name__ == "__main__":
433  options, flags = grass.parser()
434  main()
435  @endcode
436 
437  Thereafter, the global variables "options" and "flags" will be
438  dictionaries containing option/flag values, keyed by lower-case
439  option/flag names. The values in "options" are strings, those in
440  "flags" are Python booleans.
441  """
442  if not os.getenv("GISBASE"):
443  print >> sys.stderr, "You must be in GRASS GIS to run this program."
444  sys.exit(1)
445 
446  cmdline = [basename(sys.argv[0])]
447  cmdline += ['"' + arg + '"' for arg in sys.argv[1:]]
448  os.environ['CMDLINE'] = ' '.join(cmdline)
449 
450  argv = sys.argv[:]
451  name = argv[0]
452  if not os.path.isabs(name):
453  if os.sep in name or (os.altsep and os.altsep in name):
454  argv[0] = os.path.abspath(name)
455  else:
456  argv[0] = os.path.join(sys.path[0], name)
457 
458  p = Popen(['g.parser', '-s'] + argv, stdout = PIPE)
459  s = p.communicate()[0]
460  lines = s.splitlines()
461 
462  if not lines or lines[0].rstrip('\r\n') != "@ARGS_PARSED@":
463  sys.stdout.write(s)
464  sys.exit(p.returncode)
465 
466  return _parse_opts(lines[1:])
467 
468 # interface to g.tempfile
469 
470 def tempfile():
471  """!Returns the name of a temporary file, created with g.tempfile."""
472  return read_command("g.tempfile", pid = os.getpid()).strip()
473 
474 def tempdir():
475  """!Returns the name of a temporary dir, created with g.tempfile."""
476  tmp = read_command("g.tempfile", pid = os.getpid()).strip()
477  try_remove(tmp)
478  os.mkdir(tmp)
479 
480  return tmp
481 
482 # key-value parsers
483 
484 def parse_key_val(s, sep = '=', dflt = None, val_type = None, vsep = None):
485  """!Parse a string into a dictionary, where entries are separated
486  by newlines and the key and value are separated by `sep' (default: `=')
487 
488  @param s string to be parsed
489  @param sep key/value separator
490  @param dflt default value to be used
491  @param val_type value type (None for no cast)
492  @param vsep vertical separator (default os.linesep)
493 
494  @return parsed input (dictionary of keys/values)
495  """
496  result = {}
497 
498  if not s:
499  return result
500 
501  if vsep:
502  lines = s.split(vsep)
503  try:
504  lines.remove('\n')
505  except ValueError:
506  pass
507  else:
508  lines = s.splitlines()
509 
510  for line in lines:
511  kv = line.split(sep, 1)
512  k = kv[0].strip()
513  if len(kv) > 1:
514  v = kv[1]
515  else:
516  v = dflt
517  if val_type:
518  result[k] = val_type(v)
519  else:
520  result[k] = v
521  return result
522 
523 # interface to g.gisenv
524 
525 def gisenv():
526  """!Returns the output from running g.gisenv (with no arguments), as a
527  dictionary. Example:
528 
529  \code
530  >>> env = grass.gisenv()
531  >>> print env['GISDBASE']
532  /opt/grass-data
533  \endcode
534 
535  @return list of GRASS variables
536  """
537  s = read_command("g.gisenv", flags='n')
538  return parse_key_val(s)
539 
540 # interface to g.region
541 
542 def region():
543  """!Returns the output from running "g.region -g", as a
544  dictionary. Example:
545 
546  \code
547  >>> region = grass.region()
548  >>> [region[key] for key in "nsew"]
549  [228500.0, 215000.0, 645000.0, 630000.0]
550  >>> (region['nsres'], region['ewres'])
551  (10.0, 10.0)
552  \endcode
553 
554  @return dictionary of region values
555  """
556  s = read_command("g.region", flags='g')
557  reg = parse_key_val(s, val_type = float)
558  for k in ['rows', 'cols']:
559  reg[k] = int(reg[k])
560  return reg
561 
563  """!Copies the current region to a temporary region with "g.region save=",
564  then sets WIND_OVERRIDE to refer to that region. Installs an atexit
565  handler to delete the temporary region upon termination.
566  """
567  name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
568  run_command("g.region", save = name, overwrite = True)
569  os.environ['WIND_OVERRIDE'] = name
570  atexit.register(del_temp_region)
571 
573  """!Unsets WIND_OVERRIDE and removes any region named by it."""
574  try:
575  name = os.environ.pop('WIND_OVERRIDE')
576  run_command("g.remove", quiet = True, region = name)
577  except:
578  pass
579 
580 # interface to g.findfile
581 
582 def find_file(name, element = 'cell', mapset = None):
583  """!Returns the output from running g.findfile as a
584  dictionary. Example:
585 
586  \code
587  >>> result = grass.find_file('fields', element = 'vector')
588  >>> print result['fullname']
589  fields@PERMANENT
590  >>> print result['file']
591  /opt/grass-data/spearfish60/PERMANENT/vector/fields
592  \endcode
593 
594  @param name file name
595  @param element element type (default 'cell')
596  @param mapset mapset name (default all mapsets in search path)
597 
598  @return parsed output of g.findfile
599  """
600  s = read_command("g.findfile", flags='n', element = element, file = name, mapset = mapset)
601  return parse_key_val(s)
602 
603 # interface to g.list
604 
605 def list_grouped(type, check_search_path = True):
606  """!List elements grouped by mapsets.
607 
608  Returns the output from running g.list, as a dictionary where the
609  keys are mapset names and the values are lists of maps in that
610  mapset. Example:
611 
612  @code
613  >>> grass.list_grouped('rast')['PERMANENT']
614  ['aspect', 'erosion1', 'quads', 'soils', 'strm.dist', ...
615  @endcode
616 
617  @param type element type (rast, vect, rast3d, region, ...)
618  @param check_search_path True to add mapsets for the search path with no found elements
619 
620  @return directory of mapsets/elements
621  """
622  dashes_re = re.compile("^----+$")
623  mapset_re = re.compile("<(.*)>")
624  result = {}
625  if check_search_path:
626  for mapset in mapsets(search_path = True):
627  result[mapset] = []
628 
629  mapset = None
630  for line in read_command("g.list", type = type).splitlines():
631  if line == "":
632  continue
633  if dashes_re.match(line):
634  continue
635  m = mapset_re.search(line)
636  if m:
637  mapset = m.group(1)
638  if mapset not in result.keys():
639  result[mapset] = []
640  continue
641  if mapset:
642  result[mapset].extend(line.split())
643 
644  return result
645 
646 def _concat(xs):
647  result = []
648  for x in xs:
649  result.extend(x)
650  return result
651 
652 def list_pairs(type):
653  """!List of elements as tuples.
654 
655  Returns the output from running g.list, as a list of (map, mapset)
656  pairs. Example:
657 
658  @code
659  >>> grass.list_pairs('rast')
660  [('aspect', 'PERMANENT'), ('erosion1', 'PERMANENT'), ('quads', 'PERMANENT'), ...
661  @endcode
662 
663  @param type element type (rast, vect, rast3d, region, ...)
664 
665  @return list of tuples (map, mapset)
666  """
667  return _concat([[(map, mapset) for map in maps]
668  for mapset, maps in list_grouped(type).iteritems()])
669 
670 def list_strings(type):
671  """!List of elements as strings.
672 
673  Returns the output from running g.list, as a list of qualified
674  names. Example:
675 
676  @code
677  >>> grass.list_strings('rast')
678  ['aspect@PERMANENT', 'erosion1@PERMANENT', 'quads@PERMANENT', 'soils@PERMANENT', ...
679  @endcode
680 
681  @param type element type
682 
683  @return list of strings ('map@@mapset')
684  """
685  return ["%s@%s" % pair for pair in list_pairs(type)]
686 
687 # interface to g.mlist
688 
689 def mlist_grouped(type, pattern = None, check_search_path = True):
690  """!List of elements grouped by mapsets.
691 
692  Returns the output from running g.mlist, as a dictionary where the
693  keys are mapset names and the values are lists of maps in that
694  mapset. Example:
695 
696  @code
697  >>> grass.mlist_grouped('rast', pattern='r*')['PERMANENT']
698  ['railroads', 'roads', 'rstrct.areas', 'rushmore']
699  @endcode
700 
701  @param type element type (rast, vect, rast3d, region, ...)
702  @param pattern pattern string
703  @param check_search_path True to add mapsets for the search path with no found elements
704 
705  @return directory of mapsets/elements
706  """
707  result = {}
708  if check_search_path:
709  for mapset in mapsets(search_path = True):
710  result[mapset] = []
711 
712  mapset = None
713  for line in read_command("g.mlist", flags = "m",
714  type = type, pattern = pattern).splitlines():
715  try:
716  name, mapset = line.split('@')
717  except ValueError:
718  warning(_("Invalid element '%s'") % line)
719  continue
720 
721  if mapset in result:
722  result[mapset].append(name)
723  else:
724  result[mapset] = [name, ]
725 
726  return result
727 
728 # color parsing
729 
730 named_colors = {
731  "white": (1.00, 1.00, 1.00),
732  "black": (0.00, 0.00, 0.00),
733  "red": (1.00, 0.00, 0.00),
734  "green": (0.00, 1.00, 0.00),
735  "blue": (0.00, 0.00, 1.00),
736  "yellow": (1.00, 1.00, 0.00),
737  "magenta": (1.00, 0.00, 1.00),
738  "cyan": (0.00, 1.00, 1.00),
739  "aqua": (0.00, 0.75, 0.75),
740  "grey": (0.75, 0.75, 0.75),
741  "gray": (0.75, 0.75, 0.75),
742  "orange": (1.00, 0.50, 0.00),
743  "brown": (0.75, 0.50, 0.25),
744  "purple": (0.50, 0.00, 1.00),
745  "violet": (0.50, 0.00, 1.00),
746  "indigo": (0.00, 0.50, 1.00)}
747 
748 def parse_color(val, dflt = None):
749  """!Parses the string "val" as a GRASS colour, which can be either one of
750  the named colours or an R:G:B tuple e.g. 255:255:255. Returns an
751  (r,g,b) triple whose components are floating point values between 0
752  and 1. Example:
753 
754  \code
755  >>> grass.parse_color("red")
756  (1.0, 0.0, 0.0)
757  >>> grass.parse_color("255:0:0")
758  (1.0, 0.0, 0.0)
759  \endcode
760 
761  @param val color value
762  @param dflt default color value
763 
764  @return tuple RGB
765  """
766  if val in named_colors:
767  return named_colors[val]
768 
769  vals = val.split(':')
770  if len(vals) == 3:
771  return tuple(float(v) / 255 for v in vals)
772 
773  return dflt
774 
775 # check GRASS_OVERWRITE
776 
777 def overwrite():
778  """!Return True if existing files may be overwritten"""
779  owstr = 'GRASS_OVERWRITE'
780  return owstr in os.environ and os.environ[owstr] != '0'
781 
782 # check GRASS_VERBOSE
783 
784 def verbosity():
785  """!Return the verbosity level selected by GRASS_VERBOSE"""
786  vbstr = os.getenv('GRASS_VERBOSE')
787  if vbstr:
788  return int(vbstr)
789  else:
790  return 2
791 
792 ## various utilities, not specific to GRASS
793 
794 # basename inc. extension stripping
795 
796 def basename(path, ext = None):
797  """!Remove leading directory components and an optional extension
798  from the specified path
799 
800  @param path path
801  @param ext extension
802  """
803  name = os.path.basename(path)
804  if not ext:
805  return name
806  fs = name.rsplit('.', 1)
807  if len(fs) > 1 and fs[1].lower() == ext:
808  name = fs[0]
809  return name
810 
811 # find a program (replacement for "which")
812 
813 def find_program(pgm, args = []):
814  """!Attempt to run a program, with optional arguments.
815 
816  @param pgm program name
817  @param args list of arguments
818 
819  @return False if the attempt failed due to a missing executable
820  @return True otherwise
821  """
822  nuldev = file(os.devnull, 'w+')
823  try:
824  ret = call([pgm] + args, stdin = nuldev, stdout = nuldev, stderr = nuldev)
825  if ret == 0:
826  found = True
827  else:
828  found = False
829  except:
830  found = False
831  nuldev.close()
832 
833  return found
834 
835 # try to remove a file, without complaints
836 
837 def try_remove(path):
838  """!Attempt to remove a file; no exception is generated if the
839  attempt fails.
840 
841  @param path path to file to remove
842  """
843  try:
844  os.remove(path)
845  except:
846  pass
847 
848 # try to remove a directory, without complaints
849 
850 def try_rmdir(path):
851  """!Attempt to remove a directory; no exception is generated if the
852  attempt fails.
853 
854  @param path path to directory to remove
855  """
856  try:
857  os.rmdir(path)
858  except:
859  shutil.rmtree(path, ignore_errors = True)
860 
862  """!Convert DMS to float.
863 
864  @param s DMS value
865 
866  @return float value
867  """
868  return sum(float(x) / 60 ** n for (n, x) in enumerate(s.split(':')))
869 
870 # interface to g.mapsets
871 
872 def mapsets(search_path = False):
873  """!List available mapsets
874 
875  @param searchPatch True to list mapsets only in search path
876 
877  @return list of mapsets
878  """
879  if search_path:
880  flags = 'p'
881  else:
882  flags = 'l'
883  mapsets = read_command('g.mapsets',
884  flags = flags,
885  fs = 'newline',
886  quiet = True)
887  if not mapsets:
888  fatal(_("Unable to list mapsets"))
889 
890  return mapsets.splitlines()
891 
892 # interface to `g.proj -c`
893 
894 def create_location(dbase, location,
895  epsg = None, proj4 = None, filename = None, wkt = None,
896  datum = None, desc = None):
897  """!Create new location
898 
899  Raise ScriptError on error.
900 
901  @param dbase path to GRASS database
902  @param location location name to create
903  @param epgs if given create new location based on EPSG code
904  @param proj4 if given create new location based on Proj4 definition
905  @param filename if given create new location based on georeferenced file
906  @param wkt if given create new location based on WKT definition (path to PRJ file)
907  @param datum datum transformation parameters (used for epsg and proj4)
908  @param desc description of the location (creates MYNAME file)
909  """
910  gisdbase = None
911  if epsg or proj4 or filename or wkt:
912  gisdbase = gisenv()['GISDBASE']
913  run_command('g.gisenv',
914  set = 'GISDBASE=%s' % dbase)
915  if not os.path.exists(dbase):
916  os.mkdir(dbase)
917 
918  kwargs = dict()
919  if datum:
920  kwargs['datum'] = datum
921 
922  if epsg:
923  ps = pipe_command('g.proj',
924  quiet = True,
925  flags = 'c',
926  epsg = epsg,
927  location = location,
928  stderr = PIPE,
929  **kwargs)
930  elif proj4:
931  ps = pipe_command('g.proj',
932  quiet = True,
933  flags = 'c',
934  proj4 = proj4,
935  location = location,
936  stderr = PIPE,
937  **kwargs)
938  elif filename:
939  ps = pipe_command('g.proj',
940  quiet = True,
941  flags = 'c',
942  georef = filename,
943  location = location,
944  stderr = PIPE)
945  elif wkt:
946  ps = pipe_command('g.proj',
947  quiet = True,
948  flags = 'c',
949  wkt = wkt,
950  location = location,
951  stderr = PIPE)
952  else:
953  _create_location_xy(dbase, location)
954 
955  if epsg or proj4 or filename or wkt:
956  error = ps.communicate()[1]
957  run_command('g.gisenv',
958  set = 'GISDBASE=%s' % gisdbase)
959 
960  if ps.returncode != 0 and error:
961  raise ScriptError(repr(error))
962 
963  try:
964  fd = codecs.open(os.path.join(dbase, location,
965  'PERMANENT', 'MYNAME'),
966  encoding = 'utf-8', mode = 'w')
967  if desc:
968  fd.write(desc + os.linesep)
969  else:
970  fd.write(os.linesep)
971  fd.close()
972  except OSError, e:
973  raise ScriptError(repr(e))
974 
975 def _create_location_xy(database, location):
976  """!Create unprojected location
977 
978  Raise ScriptError on error.
979 
980  @param database GRASS database where to create new location
981  @param location location name
982  """
983  cur_dir = os.getcwd()
984  try:
985  os.chdir(database)
986  os.mkdir(location)
987  os.mkdir(os.path.join(location, 'PERMANENT'))
988 
989  # create DEFAULT_WIND and WIND files
990  regioninfo = ['proj: 0',
991  'zone: 0',
992  'north: 1',
993  'south: 0',
994  'east: 1',
995  'west: 0',
996  'cols: 1',
997  'rows: 1',
998  'e-w resol: 1',
999  'n-s resol: 1',
1000  'top: 1',
1001  'bottom: 0',
1002  'cols3: 1',
1003  'rows3: 1',
1004  'depths: 1',
1005  'e-w resol3: 1',
1006  'n-s resol3: 1',
1007  't-b resol: 1']
1008 
1009  defwind = open(os.path.join(location,
1010  "PERMANENT", "DEFAULT_WIND"), 'w')
1011  for param in regioninfo:
1012  defwind.write(param + '%s' % os.linesep)
1013  defwind.close()
1014 
1015  shutil.copy(os.path.join(location, "PERMANENT", "DEFAULT_WIND"),
1016  os.path.join(location, "PERMANENT", "WIND"))
1017 
1018  os.chdir(cur_dir)
1019  except OSError, e:
1020  raise ScriptError(repr(e))
1021 
1022 # interface to g.version
1023 
1024 def version():
1025  """!Get GRASS version as dictionary
1026 
1027  @code
1028  print version()
1029 
1030  {'date': '2011', 'libgis_date': '2011-04-13 13:19:03 +0200 (Wed, 13 Apr 2011)',
1031  'version': '6.4.2svn', 'libgis_revision': '45934', 'revision': '47445'}
1032  @endcode
1033  """
1034  data = parse_command('g.version',
1035  flags = 'rg')
1036  for k, v in data.iteritems():
1037  data[k.strip()] = v.replace('"', '').strip()
1038 
1039  return data
1040 
1041 # get debug_level
1042 if find_program('g.gisenv', ['--help']):
1043  debug_level = int(gisenv().get('DEBUG', 0))