utils.py 4.7 KB

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