utils.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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():
  103. """Get list of available/accessible mapsets
  104. @return ([available mapsets], [accessible mapsets])
  105. """
  106. all_mapsets = []
  107. accessible_mapsets = []
  108. ### FIXME
  109. # problem using Command here (see preferences.py)
  110. # cmd = gcmd.Command(['g.mapsets', '-l'])
  111. cmd = subprocess.Popen(['g.mapsets' + globalvar.EXT_BIN, '-l'],
  112. stdout=subprocess.PIPE)
  113. try:
  114. # for mset in cmd.ReadStdOutput()[0].split(' '):
  115. for line in cmd.stdout.readlines():
  116. for mset in line.strip('%s' % os.linesep).split(' '):
  117. if len(mset) == 0:
  118. continue
  119. all_mapsets.append(mset)
  120. except:
  121. raise gcmd.CmdError('Unable to get list of available mapsets.')
  122. # cmd = gcmd.Command(['g.mapsets', '-p'])
  123. cmd = subprocess.Popen(['g.mapsets' + globalvar.EXT_BIN, '-p'],
  124. stdout=subprocess.PIPE)
  125. try:
  126. # for mset in cmd.ReadStdOutput()[0].split(' '):
  127. for line in cmd.stdout.readlines():
  128. for mset in line.strip('%s' % os.linesep).split(' '):
  129. if len(mset) == 0:
  130. continue
  131. accessible_mapsets.append(mset)
  132. except:
  133. raise gcmd.CmdError('Unable to get list of accessible mapsets.')
  134. ListSortLower(all_mapsets)
  135. return (all_mapsets, accessible_mapsets)
  136. def ListSortLower(list):
  137. """Sort list items (not case-sensitive)"""
  138. list.sort(cmp=lambda x, y: cmp(x.lower(), y.lower()))
  139. def reexec_with_pythonw():
  140. """Re-execute Python on Mac OS"""
  141. if sys.platform == 'darwin' and \
  142. not sys.executable.endswith('MacOS/Python'):
  143. print >> sys.stderr, 're-executing using pythonw'
  144. os.execvp('pythonw', ['pythonw', __file__] + sys.argv[1:])