grass.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. import os
  2. import sys
  3. import types
  4. import subprocess
  5. import re
  6. import atexit
  7. # GRASS-oriented interface to subprocess module
  8. _popen_args = ["bufsize", "executable", "stdin", "stdout", "stderr",
  9. "preexec_fn", "close_fds", "cwd", "env",
  10. "universal_newlines", "startupinfo", "creationflags"]
  11. def _make_val(val):
  12. if isinstance(val, types.StringType):
  13. return val
  14. if isinstance(val, types.ListType):
  15. return ",".join(map(_make_val, val))
  16. if isinstance(val, types.TupleType):
  17. return _make_val(list(val))
  18. return str(val)
  19. def make_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, **options):
  20. args = [prog]
  21. if overwrite:
  22. args.append("--o")
  23. if quiet:
  24. args.append("--q")
  25. if verbose:
  26. args.append("--v")
  27. if flags:
  28. args.append("-%s" % flags)
  29. for opt, val in options.iteritems():
  30. if val != None:
  31. args.append("%s=%s" % (opt, _make_val(val)))
  32. return args
  33. def start_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, **kwargs):
  34. options = {}
  35. popts = {}
  36. for opt, val in kwargs.iteritems():
  37. if opt in _popen_args:
  38. popts[opt] = val
  39. else:
  40. options[opt] = val
  41. args = make_command(prog, flags, overwrite, quiet, verbose, **options)
  42. return subprocess.Popen(args, **popts)
  43. def run_command(*args, **kwargs):
  44. ps = start_command(*args, **kwargs)
  45. return ps.wait()
  46. def pipe_command(*args, **kwargs):
  47. kwargs['stdout'] = subprocess.PIPE
  48. return start_command(*args, **kwargs)
  49. def read_command(*args, **kwargs):
  50. ps = pipe_command(*args, **kwargs)
  51. return ps.communicate()[0]
  52. def exec_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, env = None, **kwargs):
  53. args = make_command(prog, flags, overwrite, quiet, verbose, **kwargs)
  54. if env == None:
  55. env = os.environ
  56. os.execvpe(prog, args, env)
  57. # interface to g.message
  58. def message(msg, flag = None):
  59. run_command("g.message", flags = flag, message = msg)
  60. def debug(msg):
  61. message(msg, flag = 'd')
  62. def verbose(msg):
  63. message(msg, flag = 'v')
  64. def info(msg):
  65. message(msg, flag = 'i')
  66. def warning(msg):
  67. message(msg, flag = 'w')
  68. def error(msg):
  69. message(msg, flag = 'e')
  70. def fatal(msg):
  71. error(msg)
  72. sys.exit(1)
  73. # interface to g.parser
  74. def _parse_env():
  75. options = {}
  76. flags = {}
  77. for var, val in os.environ.iteritems():
  78. if var.startswith("GIS_OPT_"):
  79. opt = var.replace("GIS_OPT_", "", 1).lower()
  80. options[opt] = val;
  81. if var.startswith("GIS_FLAG_"):
  82. flg = var.replace("GIS_FLAG_", "", 1).lower()
  83. flags[flg] = bool(int(val));
  84. return (options, flags)
  85. def parser():
  86. if not os.getenv("GISBASE"):
  87. print >> sys.stderr, "You must be in GRASS GIS to run this program."
  88. sys.exit(1)
  89. if len(sys.argv) > 1 and sys.argv[1] == "@ARGS_PARSED@":
  90. return _parse_env()
  91. argv = sys.argv[:]
  92. name = argv[0]
  93. if not os.path.isabs(name):
  94. if os.sep in name or (os.altsep and os.altsep in name):
  95. argv[0] = os.path.abspath(name)
  96. else:
  97. argv[0] = os.path.join(sys.path[0], name)
  98. os.execvp("g.parser", [name] + argv)
  99. raise OSError("error executing g.parser")
  100. # interface to g.tempfile
  101. def tempfile():
  102. return read_command("g.tempfile", pid = os.getpid()).strip()
  103. # key-value parsers
  104. def parse_key_val(s, sep = '=', dflt = None):
  105. result = {}
  106. for line in s.splitlines():
  107. kv = line.split(sep, 1)
  108. k = kv[0].strip()
  109. if len(kv) > 1:
  110. v = kv[1]
  111. else:
  112. v = dflt
  113. result[k] = v
  114. return result
  115. _kv_regex = None
  116. def parse_key_val2(s):
  117. global _kv_regex
  118. if _kv_regex == None:
  119. _kv_regex = re.compile("([^=]+)='(.*)';?")
  120. result = []
  121. for line in s.splitlines():
  122. m = _kv_regex.match(line)
  123. if m != None:
  124. result.append(m.groups())
  125. else:
  126. result.append(line.split('=', 1))
  127. return dict(result)
  128. # interface to g.gisenv
  129. def gisenv():
  130. return parse_key_val2(read_command("g.gisenv"))
  131. # interface to g.region
  132. def region():
  133. s = read_command("g.region", flags='g')
  134. return parse_key_val(s)
  135. def use_temp_region():
  136. name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
  137. run_command("g.region", save = name)
  138. os.environ['WIND_OVERRIDE'] = name
  139. atexit.register(del_temp_region)
  140. def del_temp_region():
  141. try:
  142. name = os.environ.pop('WIND_OVERRIDE')
  143. run_command("g.remove", quiet = True, region = name)
  144. except:
  145. pass
  146. # interface to g.findfile
  147. def find_file(name, element = 'cell', mapset = None):
  148. s = read_command("g.findfile", element = element, file = name, mapset = mapset)
  149. return parse_key_val2(s)
  150. # interface to g.list
  151. def list_grouped(type):
  152. dashes_re = re.compile("^----+$")
  153. mapset_re = re.compile("<(.*)>:$")
  154. result = {}
  155. mapset = None
  156. for line in read_command("g.list", type = type).splitlines():
  157. if line == "":
  158. continue
  159. if dashes_re.match(line):
  160. continue
  161. m = mapset_re.search(line)
  162. if m:
  163. mapset = m.group(1)
  164. result[mapset] = []
  165. continue
  166. if mapset:
  167. result[mapset].extend(line.split())
  168. return result
  169. def _concat(xs):
  170. result = []
  171. for x in xs:
  172. result.extend(x)
  173. return result
  174. def list_pairs(type):
  175. return _concat([[(map, mapset) for map in maps]
  176. for mapset, maps in list_grouped(type).iteritems()])
  177. def list_strings(type):
  178. return ["%s@%s" % pair for pair in list_pairs(type)]
  179. # color parsing
  180. named_colors = {
  181. "white": (1.00, 1.00, 1.00),
  182. "black": (0.00, 0.00, 0.00),
  183. "red": (1.00, 0.00, 0.00),
  184. "green": (0.00, 1.00, 0.00),
  185. "blue": (0.00, 0.00, 1.00),
  186. "yellow": (1.00, 1.00, 0.00),
  187. "magenta": (1.00, 0.00, 1.00),
  188. "cyan": (0.00, 1.00, 1.00),
  189. "aqua": (0.00, 0.75, 0.75),
  190. "grey": (0.75, 0.75, 0.75),
  191. "gray": (0.75, 0.75, 0.75),
  192. "orange": (1.00, 0.50, 0.00),
  193. "brown": (0.75, 0.50, 0.25),
  194. "purple": (0.50, 0.00, 1.00),
  195. "violet": (0.50, 0.00, 1.00),
  196. "indigo": (0.00, 0.50, 1.00)}
  197. def parse_color(val, dflt = None):
  198. if val in named_colors:
  199. return named_colors[val]
  200. vals = val.split(':')
  201. if len(vals) == 3:
  202. return tuple(float(v) / 255 for v in vals)
  203. return dflt
  204. # check GRASS_OVERWRITE
  205. def overwrite():
  206. owstr = 'GRASS_OVERWRITE'
  207. return owstr in os.environ and os.environ[owstr] != '0'
  208. ## various utilities, not specific to GRASS
  209. # basename inc. extension stripping
  210. def basename(path, ext = None):
  211. name = os.path.basename(path)
  212. if not ext:
  213. return name
  214. fs = name.rsplit('.', 1)
  215. if len(fs) > 1 and fs[1].lower() == ext:
  216. name = fs[0]
  217. return name
  218. # find a program (replacement for "which")
  219. def find_program(pgm):
  220. nuldev = file(os.devnull, 'w+')
  221. try:
  222. subprocess.call([pgm], stdin = nuldev, stdout = nuldev, stderr = nuldev)
  223. found = True
  224. except:
  225. found = False
  226. nuldev.close()
  227. return found
  228. # try to remove a file, without complaints
  229. def try_remove(path):
  230. try:
  231. os.remove(path)
  232. except:
  233. pass
  234. # try to remove a directory, without complaints
  235. def try_rmdir(path):
  236. try:
  237. os.rmdir(path)
  238. except:
  239. pass