utils.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. """
  2. @package utils.py
  3. @brief Misc utilities for GRASS wxPython GUI
  4. (C) 2007-2008 by the GRASS Development Team
  5. This program is free software under the GNU General Public
  6. License (>=v2). Read the file COPYING that comes with GRASS
  7. for details.
  8. @author Martin Landa, Jachym Cepicky
  9. @date 2007-2008
  10. """
  11. import os
  12. import sys
  13. import grass
  14. import globalvar
  15. import gcmd
  16. import grassenv
  17. try:
  18. import subprocess
  19. except:
  20. compatPath = os.path.join(globalvar.ETCWXDIR, "compat")
  21. sys.path.append(compatPath)
  22. import subprocess
  23. def GetTempfile(pref=None):
  24. """
  25. Creates GRASS temporary file using defined prefix.
  26. @todo Fix path on MS Windows/MSYS
  27. @param pref prefer the given path
  28. @return Path to file name (string) or None
  29. """
  30. import gcmd
  31. tempfileCmd = gcmd.Command(["g.tempfile",
  32. "pid=%d" % os.getpid()])
  33. tempfile = tempfileCmd.ReadStdOutput()[0].strip()
  34. # FIXME
  35. # ugly hack for MSYS (MS Windows)
  36. if subprocess.mswindows:
  37. tempfile = tempfile.replace("/", "\\")
  38. try:
  39. path, file = os.path.split(tempfile)
  40. if pref:
  41. return os.path.join(pref, file)
  42. else:
  43. return tempfile
  44. except:
  45. return None
  46. def GetLayerNameFromCmd(dcmd, fullyQualified=False, param=None,
  47. layerType=None):
  48. """Get map name from GRASS command
  49. @param dcmd GRASS command (given as list)
  50. @param fullyQualified change map name to be fully qualified
  51. @param force parameter otherwise 'input'/'map'
  52. @param update change map name in command
  53. @param layerType check also layer type ('raster', 'vector', '3d-raster', ...)
  54. @return map name
  55. @return '' if no map name found in command
  56. """
  57. mapname = ''
  58. if len(dcmd) < 1:
  59. return mapname
  60. if 'd.grid' == dcmd[0]:
  61. mapname = 'grid'
  62. elif 'd.geodesic' in dcmd[0]:
  63. mapname = 'geodesic'
  64. elif 'd.rhumbline' in dcmd[0]:
  65. mapname = 'rhumb'
  66. elif 'labels=' in dcmd[0]:
  67. mapname = dcmd[idx].split('=')[1]+' labels'
  68. else:
  69. for idx in range(len(dcmd)):
  70. if param and param in dcmd[idx]:
  71. break
  72. elif not param:
  73. if 'map=' in dcmd[idx] or \
  74. 'input=' in dcmd[idx] or \
  75. 'red=' in dcmd[idx] or \
  76. 'h_map=' in dcmd[idx] or \
  77. 'reliefmap' in dcmd[idx]:
  78. break
  79. if idx < len(dcmd):
  80. mapname = dcmd[idx].split('=')[1]
  81. if fullyQualified and '@' not in mapname:
  82. if layerType in ('raster', 'vector', '3d-raster'):
  83. try:
  84. if layerType == 'raster':
  85. findType = 'cell'
  86. else:
  87. findType = layerType
  88. result = grass.find_file(mapname, element=findType)
  89. except AttributeError, e: # not found
  90. return ''
  91. if result:
  92. mapname = result['fullname']
  93. else:
  94. mapname += '@' + grassenv.GetGRASSVariable('MAPSET')
  95. else:
  96. mapname += '@' + grassenv.GetGRASSVariable('MAPSET')
  97. dcmd[idx] = dcmd[idx].split('=')[0] + '=' + mapname
  98. return mapname
  99. def GetValidLayerName(name):
  100. """Make layer name SQL compliant, based on G_str_to_sql()
  101. @todo: Better use directly GRASS Python SWIG...
  102. """
  103. retName = str(name).strip()
  104. # check if name is fully qualified
  105. if '@' in retName:
  106. retName, mapset = retName.split('@')
  107. else:
  108. mapset = None
  109. for c in retName:
  110. # c = toascii(c)
  111. if not (c >= 'A' and c <= 'Z') and \
  112. not (c >= 'a' and c <= 'z') and \
  113. not (c >= '0' and c <= '9'):
  114. c = '_'
  115. if not (retName[0] >= 'A' and retName[0] <= 'Z') and \
  116. not (retName[0] >= 'a' and retName[0] <= 'z'):
  117. retName = 'x' + retName[1:]
  118. if mapset:
  119. retName = retName + '@' + mapset
  120. return retName
  121. def ListOfCatsToRange(cats):
  122. """Convert list of category number to range(s)
  123. Used for example for d.vect cats=[range]
  124. @param cats category list
  125. @return category range string
  126. @return '' on error
  127. """
  128. catstr = ''
  129. try:
  130. cats = map(int, cats)
  131. except:
  132. return catstr
  133. i = 0
  134. while i < len(cats):
  135. next = 0
  136. j = i + 1
  137. while j < len(cats):
  138. if cats[i + next] == cats[j] - 1:
  139. next += 1
  140. else:
  141. break
  142. j += 1
  143. if next > 1:
  144. catstr += '%d-%d,' % (cats[i], cats[i + next])
  145. i += next + 1
  146. else:
  147. catstr += '%d,' % (cats[i])
  148. i += 1
  149. return catstr.strip(',')
  150. def ListOfMapsets(all=False):
  151. """Get list of available/accessible mapsets
  152. @param all if True get list of all mapsets
  153. @return list of mapsets
  154. """
  155. mapsets = []
  156. ### FIXME
  157. # problem using Command here (see preferences.py)
  158. # cmd = gcmd.Command(['g.mapsets', '-l'])
  159. if all:
  160. cmd = subprocess.Popen(['g.mapsets' + globalvar.EXT_BIN, '-l'],
  161. stdout=subprocess.PIPE)
  162. try:
  163. # for mset in cmd.ReadStdOutput()[0].split(' '):
  164. for line in cmd.stdout.readlines():
  165. for mset in line.strip('%s' % os.linesep).split(' '):
  166. if len(mset) == 0:
  167. continue
  168. mapsets.append(mset)
  169. except:
  170. raise gcmd.CmdError(_('Unable to get list of available mapsets.'))
  171. else:
  172. # cmd = gcmd.Command(['g.mapsets', '-p'])
  173. cmd = subprocess.Popen(['g.mapsets' + globalvar.EXT_BIN, '-p'],
  174. stdout=subprocess.PIPE)
  175. try:
  176. # for mset in cmd.ReadStdOutput()[0].split(' '):
  177. for line in cmd.stdout.readlines():
  178. for mset in line.strip('%s' % os.linesep).split(' '):
  179. if len(mset) == 0:
  180. continue
  181. mapsets.append(mset)
  182. except:
  183. raise gcmd.CmdError(_('Unable to get list of accessible mapsets.'))
  184. ListSortLower(mapsets)
  185. return mapsets
  186. def ListSortLower(list):
  187. """Sort list items (not case-sensitive)"""
  188. list.sort(cmp=lambda x, y: cmp(x.lower(), y.lower()))
  189. def reexec_with_pythonw():
  190. """Re-execute Python on Mac OS"""
  191. if sys.platform == 'darwin' and \
  192. not sys.executable.endswith('MacOS/Python'):
  193. print >> sys.stderr, 're-executing using pythonw'
  194. os.execvp('pythonw', ['pythonw', __file__] + sys.argv[1:])