utils.py 5.0 KB

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