utils.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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 ListOfCatsToRange(cats):
  83. """Convert list of category number to range(s)
  84. Used for example for d.vect cats=[range]
  85. @param cats category list
  86. @return category range string
  87. @return '' on error
  88. """
  89. catstr = ''
  90. try:
  91. cats = map(int, cats)
  92. except:
  93. return catstr
  94. i = 0
  95. while i < len(cats):
  96. next = 0
  97. j = i + 1
  98. while j < len(cats):
  99. if cats[i + next] == cats[j] - 1:
  100. next += 1
  101. else:
  102. break
  103. j += 1
  104. if next > 1:
  105. catstr += '%d-%d,' % (cats[i], cats[i + next])
  106. i += next + 1
  107. else:
  108. catstr += '%d,' % (cats[i])
  109. i += 1
  110. return catstr.strip(',')
  111. def ListOfMapsets(all=False):
  112. """Get list of available/accessible mapsets
  113. @param all if True get list of all mapsets
  114. @return list of mapsets
  115. """
  116. mapsets = []
  117. ### FIXME
  118. # problem using Command here (see preferences.py)
  119. # cmd = gcmd.Command(['g.mapsets', '-l'])
  120. if all:
  121. cmd = subprocess.Popen(['g.mapsets' + globalvar.EXT_BIN, '-l'],
  122. stdout=subprocess.PIPE)
  123. try:
  124. # for mset in cmd.ReadStdOutput()[0].split(' '):
  125. for line in cmd.stdout.readlines():
  126. for mset in line.strip('%s' % os.linesep).split(' '):
  127. if len(mset) == 0:
  128. continue
  129. mapsets.append(mset)
  130. except:
  131. raise gcmd.CmdError(_('Unable to get list of available mapsets.'))
  132. else:
  133. # cmd = gcmd.Command(['g.mapsets', '-p'])
  134. cmd = subprocess.Popen(['g.mapsets' + globalvar.EXT_BIN, '-p'],
  135. stdout=subprocess.PIPE)
  136. try:
  137. # for mset in cmd.ReadStdOutput()[0].split(' '):
  138. for line in cmd.stdout.readlines():
  139. for mset in line.strip('%s' % os.linesep).split(' '):
  140. if len(mset) == 0:
  141. continue
  142. mapsets.append(mset)
  143. except:
  144. raise gcmd.CmdError(_('Unable to get list of accessible mapsets.'))
  145. ListSortLower(mapsets)
  146. return mapsets
  147. def ListSortLower(list):
  148. """Sort list items (not case-sensitive)"""
  149. list.sort(cmp=lambda x, y: cmp(x.lower(), y.lower()))
  150. def reexec_with_pythonw():
  151. """Re-execute Python on Mac OS"""
  152. if sys.platform == 'darwin' and \
  153. not sys.executable.endswith('MacOS/Python'):
  154. print >> sys.stderr, 're-executing using pythonw'
  155. os.execvp('pythonw', ['pythonw', __file__] + sys.argv[1:])