utils.py 6.0 KB

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