utils.py 5.2 KB

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