grass.py 5.8 KB

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