GRASS Programmer's Manual  6.5.svn(2014)-r66266
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
core/utils.py
Go to the documentation of this file.
1 """!
2 @package core.utils
3 
4 @brief Misc utilities for wxGUI
5 
6 (C) 2007-2009, 2011-2012 by the GRASS Development Team
7 
8 This program is free software under the GNU General Public License
9 (>=v2). Read the file COPYING that comes with GRASS for details.
10 
11 @author Martin Landa <landa.martin gmail.com>
12 @author Jachym Cepicky
13 """
14 
15 import os
16 import sys
17 import platform
18 import string
19 import glob
20 import shlex
21 import re
22 import locale
23 
24 from core.globalvar import ETCDIR
25 sys.path.append(os.path.join(ETCDIR, "python"))
26 
27 from grass.script import core as grass
28 from grass.script import task as gtask
29 
30 from core.gcmd import RunCommand
31 from core.debug import Debug
32 
34  """!Remove redundant whitespace from a string"""
35  return string.join(string.split(text), ' ')
36 
37 def split(s):
38  """!Platform spefic shlex.split"""
39  if sys.platform == "win32":
40  return shlex.split(s.replace('\\', r'\\'))
41  else:
42  return shlex.split(s)
43 
44 def GetTempfile(pref=None):
45  """!Creates GRASS temporary file using defined prefix.
46 
47  @todo Fix path on MS Windows/MSYS
48 
49  @param pref prefer the given path
50 
51  @return Path to file name (string) or None
52  """
53  ret = RunCommand('g.tempfile',
54  read = True,
55  pid = os.getpid())
56 
57  tempfile = ret.splitlines()[0].strip()
58 
59  # FIXME
60  # ugly hack for MSYS (MS Windows)
61  if platform.system() == 'Windows':
62  tempfile = tempfile.replace("/", "\\")
63  try:
64  path, file = os.path.split(tempfile)
65  if pref:
66  return os.path.join(pref, file)
67  else:
68  return tempfile
69  except:
70  return None
71 
72 def GetLayerNameFromCmd(dcmd, fullyQualified = False, param = None,
73  layerType = None):
74  """!Get map name from GRASS command
75 
76  Parameter dcmd can be modified when first parameter is not
77  defined.
78 
79  @param dcmd GRASS command (given as list)
80  @param fullyQualified change map name to be fully qualified
81  @param param params directory
82  @param layerType check also layer type ('raster', 'vector', '3d-raster', ...)
83 
84  @return tuple (name, found)
85  """
86  mapname = ''
87  found = True
88 
89  if len(dcmd) < 1:
90  return mapname, False
91 
92  if 'd.grid' == dcmd[0]:
93  mapname = 'grid'
94  elif 'd.geodesic' in dcmd[0]:
95  mapname = 'geodesic'
96  elif 'd.rhumbline' in dcmd[0]:
97  mapname = 'rhumb'
98  elif 'labels=' in dcmd[0]:
99  mapname = dcmd[idx].split('=')[1] + ' labels'
100  else:
101  params = list()
102  for idx in range(len(dcmd)):
103  try:
104  p, v = dcmd[idx].split('=', 1)
105  except ValueError:
106  continue
107 
108  if p == param:
109  params = [(idx, p, v)]
110  break
111 
112  if p in ('map', 'input',
113  'red', 'blue', 'green',
114  'h_map', 's_map', 'i_map',
115  'reliefmap', 'labels'):
116  params.append((idx, p, v))
117 
118  if len(params) < 1:
119  if len(dcmd) > 1:
120  i = 1
121  while i < len(dcmd):
122  if '=' not in dcmd[i] and not dcmd[i].startswith('-'):
123  task = gtask.parse_interface(dcmd[0])
124  # this expects the first parameter to be the right one
125  p = task.get_options()['params'][0].get('name', '')
126  params.append((i, p, dcmd[i]))
127  break
128  i += 1
129  else:
130  return mapname, False
131 
132  if len(params) < 1:
133  return mapname, False
134 
135  # need to add mapset for all maps
136  mapsets = {}
137  for i, p, v in params:
138  mapname = v
139  mapset = ''
140  if fullyQualified and '@' not in mapname:
141  if layerType in ('raster', 'vector', '3d-raster', 'rgb', 'his'):
142  try:
143  if layerType in ('raster', 'rgb', 'his'):
144  findType = 'cell'
145  else:
146  findType = layerType
147  mapset = grass.find_file(mapname, element = findType)['mapset']
148  except AttributeError, e: # not found
149  return '', False
150  if not mapset:
151  found = False
152  else:
153  mapset = grass.gisenv()['MAPSET']
154  mapsets[i] = mapset
155 
156  # update dcmd
157  for i, p, v in params:
158  if p:
159  dcmd[i] = p + '=' + v
160  else:
161  dcmd[i] = v
162  if i in mapsets and mapsets[i]:
163  dcmd[i] += '@' + mapsets[i]
164 
165  maps = list()
166  for i, p, v in params:
167  if not p:
168  maps.append(v)
169  else:
170  maps.append(dcmd[i].split('=', 1)[1])
171  mapname = '\n'.join(maps)
172 
173  return mapname, found
174 
176  """!Make layer name SQL compliant, based on G_str_to_sql()
177 
178  @todo: Better use directly Ctypes to reuse venerable libgis C fns...
179  """
180  retName = str(name).strip()
181 
182  # check if name is fully qualified
183  if '@' in retName:
184  retName, mapset = retName.split('@')
185  else:
186  mapset = None
187 
188  cIdx = 0
189  retNameList = list(retName)
190  for c in retNameList:
191  if not (c >= 'A' and c <= 'Z') and \
192  not (c >= 'a' and c <= 'z') and \
193  not (c >= '0' and c <= '9'):
194  retNameList[cIdx] = '_'
195  cIdx += 1
196  retName = ''.join(retNameList)
197 
198  if not (retName[0] >= 'A' and retName[0] <= 'Z') and \
199  not (retName[0] >= 'a' and retName[0] <= 'z'):
200  retName = 'x' + retName[1:]
201 
202  if mapset:
203  retName = retName + '@' + mapset
204 
205  return retName
206 
208  """!Convert list of category number to range(s)
209 
210  Used for example for d.vect cats=[range]
211 
212  @param cats category list
213 
214  @return category range string
215  @return '' on error
216  """
217 
218  catstr = ''
219 
220  try:
221  cats = map(int, cats)
222  except:
223  return catstr
224 
225  i = 0
226  while i < len(cats):
227  next = 0
228  j = i + 1
229  while j < len(cats):
230  if cats[i + next] == cats[j] - 1:
231  next += 1
232  else:
233  break
234  j += 1
235 
236  if next > 1:
237  catstr += '%d-%d,' % (cats[i], cats[i + next])
238  i += next + 1
239  else:
240  catstr += '%d,' % (cats[i])
241  i += 1
242 
243  return catstr.strip(',')
244 
245 def ListOfMapsets(get = 'ordered'):
246  """!Get list of available/accessible mapsets
247 
248  @param get method ('all', 'accessible', 'ordered')
249 
250  @return list of mapsets
251  @return None on error
252  """
253  mapsets = []
254 
255  if get == 'all' or get == 'ordered':
256  ret = RunCommand('g.mapsets',
257  read = True,
258  quiet = True,
259  flags = 'l',
260  fs = 'newline')
261 
262  if ret:
263  mapsets = ret.splitlines()
264  ListSortLower(mapsets)
265  else:
266  return None
267 
268  if get == 'accessible' or get == 'ordered':
269  ret = RunCommand('g.mapsets',
270  read = True,
271  quiet = True,
272  flags = 'p',
273  fs = 'newline')
274  if ret:
275  if get == 'accessible':
276  mapsets = ret.splitlines()
277  else:
278  mapsets_accessible = ret.splitlines()
279  for mapset in mapsets_accessible:
280  mapsets.remove(mapset)
281  mapsets = mapsets_accessible + mapsets
282  else:
283  return None
284 
285  return mapsets
286 
287 def ListSortLower(list):
288  """!Sort list items (not case-sensitive)"""
289  list.sort(cmp=lambda x, y: cmp(x.lower(), y.lower()))
290 
291 def GetVectorNumberOfLayers(vector, parent = None):
292  """!Get list of vector layers
293 
294  @param vector name of vector map
295  @param parent parent window (to show dialog) or None
296  """
297  layers = []
298  if not vector:
299  return layers
300 
301  fullname = grass.find_file(name = vector, element = 'vector')['fullname']
302  if not fullname:
303  Debug.msg(5, "utils.GetVectorNumberOfLayers(): vector map '%s' not found" % vector)
304  return layers
305 
306  ret, out, msg = RunCommand('v.db.connect',
307  getErrorMsg = True,
308  read = True,
309  flags = 'g',
310  map = fullname,
311  fs = ';')
312  if ret != 0:
313  sys.stderr.write(_("Vector map <%(map)s>: %(msg)s\n") % { 'map' : fullname, 'msg' : msg })
314  return layers
315 
316  Debug.msg(1, "GetVectorNumberOfLayers(): ret %s" % ret)
317 
318  for line in out.splitlines():
319  try:
320  layer = line.split(';')[0]
321  if '/' in layer:
322  layer = layer.split('/')[0]
323  layers.append(layer)
324  except IndexError:
325  pass
326 
327  Debug.msg(3, "utils.GetVectorNumberOfLayers(): vector=%s -> %s" % \
328  (fullname, ','.join(layers)))
329 
330  return layers
331 
332 def GetAllVectorLayers(vector):
333  """!Returns list of all vector layers as strings.
334 
335  @param vector name of vector map
336  """
337  layers = []
338  if not vector:
339  return layers
340 
341  fullname = grass.find_file(name = vector, element = 'vector')['fullname']
342  if not fullname:
343  Debug.msg(3, "utils.GetAllVectorLayers(): vector map <%s> not found" % vector)
344  return layers
345 
346  ret, out, msg = RunCommand('v.category',
347  getErrorMsg = True,
348  read = True,
349  quiet = True,
350  option = 'layers',
351  input = fullname)
352 
353  if ret != 0:
354  sys.stderr.write(_("Vector map <%(map)s>: %(msg)s\n") % { 'map' : fullname, 'msg' : msg })
355  return layers
356 
357  Debug.msg(1, "utils.GetAllVectorLayers(): ret %s" % ret)
358 
359  for layer in out.splitlines():
360  layers.append(layer)
361 
362  Debug.msg(3, "utils.GetAllVectorLayers(): vector=%s -> %s" % \
363  (fullname, ','.join(layers)))
364 
365  return layers
366 
367 def Deg2DMS(lon, lat, string = True, hemisphere = True, precision = 3):
368  """!Convert deg value to dms string
369 
370  @param lon longitude (x)
371  @param lat latitude (y)
372  @param string True to return string otherwise tuple
373  @param hemisphere print hemisphere
374  @param precision seconds precision
375 
376  @return DMS string or tuple of values
377  @return empty string on error
378  """
379  try:
380  flat = float(lat)
381  flon = float(lon)
382  except ValueError:
383  if string:
384  return ''
385  else:
386  return None
387 
388  # fix longitude
389  while flon > 180.0:
390  flon -= 360.0
391  while flon < -180.0:
392  flon += 360.0
393 
394  # hemisphere
395  if hemisphere:
396  if flat < 0.0:
397  flat = abs(flat)
398  hlat = 'S'
399  else:
400  hlat = 'N'
401 
402  if flon < 0.0:
403  hlon = 'W'
404  flon = abs(flon)
405  else:
406  hlon = 'E'
407  else:
408  flat = abs(flat)
409  flon = abs(flon)
410  hlon = ''
411  hlat = ''
412 
413  slat = __ll_parts(flat, precision = precision)
414  slon = __ll_parts(flon, precision = precision)
415 
416  if string:
417  return slon + hlon + '; ' + slat + hlat
418 
419  return (slon + hlon, slat + hlat)
420 
421 def DMS2Deg(lon, lat):
422  """!Convert dms value to deg
423 
424  @param lon longitude (x)
425  @param lat latitude (y)
426 
427  @return tuple of converted values
428  @return ValueError on error
429  """
430  x = __ll_parts(lon, reverse = True)
431  y = __ll_parts(lat, reverse = True)
432 
433  return (x, y)
434 
435 def __ll_parts(value, reverse = False, precision = 3):
436  """!Converts deg to d:m:s string
437 
438  @param value value to be converted
439  @param reverse True to convert from d:m:s to deg
440  @param precision seconds precision (ignored if reverse is True)
441 
442  @return converted value (string/float)
443  @return ValueError on error (reverse == True)
444  """
445  if not reverse:
446  if value == 0.0:
447  return '%s%.*f' % ('00:00:0', precision, 0.0)
448 
449  d = int(int(value))
450  m = int((value - d) * 60)
451  s = ((value - d) * 60 - m) * 60
452  if m < 0:
453  m = '00'
454  elif m < 10:
455  m = '0' + str(m)
456  else:
457  m = str(m)
458  if s < 0:
459  s = '00.0000'
460  elif s < 10.0:
461  s = '0%.*f' % (precision, s)
462  else:
463  s = '%.*f' % (precision, s)
464 
465  return str(d) + ':' + m + ':' + s
466  else: # -> reverse
467  try:
468  d, m, s = value.split(':')
469  hs = s[-1]
470  s = s[:-1]
471  except ValueError:
472  try:
473  d, m = value.split(':')
474  hs = m[-1]
475  m = m[:-1]
476  s = '0.0'
477  except ValueError:
478  try:
479  d = value
480  hs = d[-1]
481  d = d[:-1]
482  m = '0'
483  s = '0.0'
484  except ValueError:
485  raise ValueError
486 
487  if hs not in ('N', 'S', 'E', 'W'):
488  raise ValueError
489 
490  coef = 1.0
491  if hs in ('S', 'W'):
492  coef = -1.0
493 
494  fm = int(m) / 60.0
495  fs = float(s) / (60 * 60)
496 
497  return coef * (float(d) + fm + fs)
498 
499 def GetCmdString(cmd):
500  """
501  Get GRASS command as string.
502 
503  @param cmd GRASS command given as dictionary
504 
505  @return command string
506  """
507  scmd = ''
508  if not cmd:
509  return scmd
510 
511  scmd = cmd[0]
512 
513  if 'flags' in cmd[1]:
514  for flag in cmd[1]['flags']:
515  scmd += ' -' + flag
516  for flag in ('verbose', 'quiet', 'overwrite'):
517  if flag in cmd[1] and cmd[1][flag] is True:
518  scmd += ' --' + flag
519 
520  for k, v in cmd[1].iteritems():
521  if k in ('flags', 'verbose', 'quiet', 'overwrite'):
522  continue
523  scmd += ' %s=%s' % (k, v)
524 
525  return scmd
526 
527 def CmdToTuple(cmd):
528  """!Convert command list to tuple for gcmd.RunCommand()"""
529  if len(cmd) < 1:
530  return None
531 
532  dcmd = {}
533  for item in cmd[1:]:
534  if '=' in item: # params
535  key, value = item.split('=', 1)
536  dcmd[str(key)] = str(value)
537  elif item[:2] == '--': # long flags
538  flag = item[2:]
539  if flag in ('verbose', 'quiet', 'overwrite'):
540  dcmd[str(flag)] = True
541  elif len(item) == 2 and item[0] == '-': # -> flags
542  if 'flags' not in dcmd:
543  dcmd['flags'] = ''
544  dcmd['flags'] += item[1]
545  else: # unnamed parameter
546  module = gtask.parse_interface(cmd[0])
547  dcmd[module.define_first()] = item
548 
549  return (cmd[0], dcmd)
550 
551 def PathJoin(*args):
552  """!Check path created by os.path.join"""
553  path = os.path.join(*args)
554  if platform.system() == 'Windows' and \
555  '/' in path:
556  return path[1].upper() + ':\\' + path[3:].replace('/', '\\')
557 
558  return path
559 
560 def ReadEpsgCodes(path):
561  """!Read EPSG code from the file
562 
563  @param path full path to the file with EPSG codes
564 
565  @return dictionary of EPSG code
566  @return string on error
567  """
568  epsgCodeDict = dict()
569  try:
570  try:
571  f = open(path, "r")
572  except IOError:
573  return _("failed to open '%s'" % path)
574 
575  i = 0
576  code = None
577  for line in f.readlines():
578  line = line.strip()
579  if len(line) < 1:
580  continue
581 
582  if line[0] == '#':
583  descr = line[1:].strip()
584  elif line[0] == '<':
585  code, params = line.split(" ", 1)
586  try:
587  code = int(code.replace('<', '').replace('>', ''))
588  except ValueError:
589  return e
590 
591  if code is not None:
592  epsgCodeDict[code] = (descr, params)
593  code = None
594  i += 1
595 
596  f.close()
597  except StandardError, e:
598  return e
599 
600  return epsgCodeDict
601 
602 def ReprojectCoordinates(coord, projOut, projIn = None, flags = ''):
603  """!Reproject coordinates
604 
605  @param coord coordinates given as tuple
606  @param projOut output projection
607  @param projIn input projection (use location projection settings)
608 
609  @return reprojected coordinates (returned as tuple)
610  """
611  if not projIn:
612  projIn = RunCommand('g.proj',
613  flags = 'jf',
614  read = True)
615  coors = RunCommand('m.proj',
616  flags = flags,
617  proj_in = projIn,
618  proj_out = projOut,
619  stdin = '%f|%f' % (coord[0], coord[1]),
620  read = True)
621  if coors:
622  coors = coors.split('\t')
623  e = coors[0]
624  n = coors[1].split(' ')[0].strip()
625  try:
626  proj = projOut.split(' ')[0].split('=')[1]
627  except IndexError:
628  proj = ''
629  if proj in ('ll', 'latlong', 'longlat') and 'd' not in flags:
630  return (proj, (e, n))
631  else:
632  try:
633  return (proj, (float(e), float(n)))
634  except ValueError:
635  return (None, None)
636 
637  return (None, None)
638 
640  """!Get list of GRASS locations in given dbase
641 
642  @param dbase GRASS database path
643 
644  @return list of locations (sorted)
645  """
646  listOfLocations = list()
647 
648  try:
649  for location in glob.glob(os.path.join(dbase, "*")):
650  try:
651  if os.path.join(location, "PERMANENT") in glob.glob(os.path.join(location, "*")):
652  listOfLocations.append(os.path.basename(location))
653  except:
654  pass
655  except UnicodeEncodeError, e:
656  raise e
657 
658  ListSortLower(listOfLocations)
659 
660  return listOfLocations
661 
662 def GetListOfMapsets(dbase, location, selectable = False):
663  """!Get list of mapsets in given GRASS location
664 
665  @param dbase GRASS database path
666  @param location GRASS location
667  @param selectable True to get list of selectable mapsets, otherwise all
668 
669  @return list of mapsets - sorted (PERMANENT first)
670  """
671  listOfMapsets = list()
672 
673  if selectable:
674  ret = RunCommand('g.mapset',
675  read = True,
676  flags = 'l',
677  location = location,
678  gisdbase = dbase)
679 
680  if not ret:
681  return listOfMapsets
682 
683  for line in ret.rstrip().splitlines():
684  listOfMapsets += line.split(' ')
685  else:
686  for mapset in glob.glob(os.path.join(dbase, location, "*")):
687  if os.path.isdir(mapset) and \
688  os.path.isfile(os.path.join(dbase, location, mapset, "WIND")):
689  listOfMapsets.append(os.path.basename(mapset))
690 
691  ListSortLower(listOfMapsets)
692  return listOfMapsets
693 
695  """!Get list of color tables"""
696  ret = RunCommand('r.colors',
697  read = True,
698  flags = 'l')
699  if not ret:
700  return list()
701 
702  return ret.splitlines()
703 
704 def DecodeString(string):
705  """!Decode string using system encoding
706 
707  @param string string to be decoded
708 
709  @return decoded string
710  """
711  if not string:
712  return string
713 
714  enc = locale.getdefaultlocale()[1]
715  if enc:
716  Debug.msg(5, "DecodeString(): enc=%s" % enc)
717  return string.decode(enc)
718 
719  return string
720 
721 def EncodeString(string):
722  """!Return encoded string using system locales
723 
724  @param string string to be encoded
725 
726  @return encoded string
727  """
728  if not string:
729  return string
730  enc = locale.getdefaultlocale()[1]
731  if enc:
732  Debug.msg(5, "EncodeString(): enc=%s" % enc)
733  return string.encode(enc)
734 
735  return string
736 
737 def _getGDALFormats():
738  """!Get dictionary of avaialble GDAL drivers"""
739  try:
740  ret = grass.read_command('r.in.gdal',
741  quiet = True,
742  flags = 'f')
743  except:
744  ret = None
745 
746  return _parseFormats(ret)
747 
748 def _getOGRFormats():
749  """!Get dictionary of avaialble OGR drivers"""
750  try:
751  ret = grass.read_command('v.in.ogr',
752  quiet = True,
753  flags = 'f')
754  except:
755  ret = None
756 
757  return _parseFormats(ret)
758 
759 def _parseFormats(output):
760  """!Parse r.in.gdal/v.in.ogr -f output"""
761  formats = { 'file' : list(),
762  'database' : list(),
763  'protocol' : list()
764  }
765 
766  if not output:
767  return formats
768 
769  for line in output.splitlines():
770  format = line.strip().rsplit(':', -1)[1].strip()
771  if format in ('Memory', 'Virtual Raster', 'In Memory Raster'):
772  continue
773  if format in ('PostgreSQL', 'SQLite',
774  'ODBC', 'ESRI Personal GeoDatabase',
775  'Rasterlite',
776  'PostGIS WKT Raster driver',
777  'CouchDB'):
778  formats['database'].append(format)
779  elif format in ('GeoJSON',
780  'OGC Web Coverage Service',
781  'OGC Web Map Service',
782  'WFS',
783  'GeoRSS',
784  'HTTP Fetching Wrapper'):
785  formats['protocol'].append(format)
786  else:
787  formats['file'].append(format)
788 
789  for items in formats.itervalues():
790  items.sort()
791 
792  return formats
793 
794 formats = None
795 
797  """!Get GDAL/OGR formats"""
798  global formats
799  if not formats:
800  formats = {
801  'gdal' : _getGDALFormats(),
802  'ogr' : _getOGRFormats()
803  }
804 
805  return formats
806 
808  """!Get full path to the settings directory
809  """
810  try:
811  verFd = open(os.path.join(ETCDIR, "VERSIONNUMBER"))
812  version = int(verFd.readlines()[0].split(' ')[0].split('.')[0])
813  except (IOError, ValueError, TypeError, IndexError), e:
814  sys.exit(_("ERROR: Unable to determine GRASS version. Details: %s") % e)
815 
816  verFd.close()
817 
818  # keep location of settings files rc and wx in sync with
819  # lib/init/init.sh and init.bat
820  if sys.platform == 'win32':
821  return os.path.join(os.getenv('APPDATA'), 'GRASS%d' % version)
822 
823  return os.path.join(os.getenv('HOME'), '.grass%d' % version)
824 
825 def StoreEnvVariable(key, value = None, envFile = None):
826  """!Store environmental variable
827 
828  If value is not given (is None) then environmental variable is
829  unset.
830 
831  @param key env key
832  @param value env value
833  @param envFile path to the environmental file (None for default location)
834  """
835  windows = sys.platform == 'win32'
836  if not envFile:
837  if not windows:
838  envFile = os.path.join(os.getenv('HOME'), '.grass.bashrc')
839  else:
840  gVersion = grass.version()['version'].split('.', 1)[0]
841  envFile = os.path.join(os.getenv('APPDATA'), 'GRASS%s' % gVersion, 'env.bat')
842 
843  # read env file
844  environ = dict()
845  lineSkipped = list()
846  if os.path.exists(envFile):
847  try:
848  fd = open(envFile)
849  except IOError, e:
850  sys.stderr.write(_("Unable to open file '%s'\n") % envFile)
851  return
852  for line in fd.readlines():
853  line = line.rstrip(os.linesep)
854  try:
855  k, v = map(lambda x: x.strip(), line.split(' ', 1)[1].split('=', 1))
856  except StandardError, e:
857  sys.stderr.write(_("%s: line skipped - unable to parse '%s'\n"
858  "Reason: %s\n") % (envFile, line, e))
859  lineSkipped.append(line)
860  continue
861  if k in environ:
862  sys.stderr.write(_("Duplicated key: %s\n") % k)
863  environ[k] = v
864 
865  fd.close()
866 
867  # update environmental variables
868  if value is None and key in environ:
869  del environ[key]
870  else:
871  environ[key] = value
872 
873  # write update env file
874  try:
875  fd = open(envFile, 'w')
876  except IOError, e:
877  sys.stderr.write(_("Unable to create file '%s'\n") % envFile)
878  return
879  if windows:
880  expCmd = 'set'
881  else:
882  expCmd = 'export'
883 
884  for key, value in environ.iteritems():
885  fd.write('%s %s=%s\n' % (expCmd, key, value))
886 
887  # write also skipped lines
888  for line in lineSkipped:
889  fd.write(line + os.linesep)
890 
891  fd.close()
892 
893 def SetAddOnPath(addonPath = None):
894  """!Set default AddOn path
895 
896  @addonPath path to addons (None for default)
897  """
898  gVersion = grass.version()['version'].split('.', 1)[0]
899  # update env file
900  if not addonPath:
901  if sys.platform != 'win32':
902  addonPath = os.path.join(os.path.join(os.getenv('HOME'),
903  '.grass%s' % gVersion,
904  'addons'))
905  else:
906  addonPath = os.path.join(os.path.join(os.getenv('APPDATA'),
907  'GRASS%s' % gVersion,
908  'addons'))
909 
910  StoreEnvVariable('GRASS_ADDON_PATH', addonPath)
911  os.environ['GRASS_ADDON_PATH'] = addonPath
def CmdToTuple
Convert command list to tuple for gcmd.RunCommand()
Definition: core/utils.py:527
def GetListOfLocations
Get list of GRASS locations in given dbase.
Definition: core/utils.py:639
def normalize_whitespace
Remove redundant whitespace from a string.
Definition: core/utils.py:33
wxGUI command interface
def GetCmdString
Definition: core/utils.py:499
def ListOfCatsToRange
Convert list of category number to range(s)
Definition: core/utils.py:207
def GetSettingsPath
Get full path to the settings directory.
Definition: core/utils.py:807
wxGUI debugging
def GetListOfMapsets
Get list of mapsets in given GRASS location.
Definition: core/utils.py:662
def split
Platform spefic shlex.split.
Definition: core/utils.py:37
def GetFormats
Get GDAL/OGR formats.
Definition: core/utils.py:796
def StoreEnvVariable
Store environmental variable.
Definition: core/utils.py:825
def SetAddOnPath
Set default AddOn path.
Definition: core/utils.py:893
def ListOfMapsets
Get list of available/accessible mapsets.
Definition: core/utils.py:245
def GetLayerNameFromCmd
Get map name from GRASS command.
Definition: core/utils.py:73
def EncodeString
Return encoded string using system locales.
Definition: core/utils.py:721
def ReadEpsgCodes
Read EPSG code from the file.
Definition: core/utils.py:560
def ListSortLower
Sort list items (not case-sensitive)
Definition: core/utils.py:287
def DMS2Deg
Convert dms value to deg.
Definition: core/utils.py:421
def GetValidLayerName
Make layer name SQL compliant, based on G_str_to_sql()
Definition: core/utils.py:175
def GetTempfile
Creates GRASS temporary file using defined prefix.
Definition: core/utils.py:44
def DecodeString
Decode string using system encoding.
Definition: core/utils.py:704
def GetColorTables
Get list of color tables.
Definition: core/utils.py:694
def GetAllVectorLayers
Returns list of all vector layers as strings.
Definition: core/utils.py:332
def PathJoin
Check path created by os.path.join.
Definition: core/utils.py:551
Global variables used by wxGUI.
tuple range
Definition: tools.py:1406
def ReprojectCoordinates
Reproject coordinates.
Definition: core/utils.py:602
def GetVectorNumberOfLayers
Get list of vector layers.
Definition: core/utils.py:291
def RunCommand
Run GRASS command.
Definition: gcmd.py:625
def Deg2DMS
Convert deg value to dms string.
Definition: core/utils.py:367