grass.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. 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. # interface to g.gisenv
  104. _kv_regex = re.compile("([^=]+)='(.*)';?")
  105. def gisenv():
  106. lines = read_command("g.gisenv").splitlines()
  107. return dict([_kv_regex.match(line).groups() for line in lines])
  108. # interface to g.region
  109. def region():
  110. lines = read_command("g.region", flags='g').splitlines()
  111. return dict([line.split('=',1) for line in lines])
  112. def use_temp_region():
  113. name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
  114. run_command("g.region", save = name)
  115. os.environ['WIND_OVERRIDE'] = name
  116. atexit.register(del_temp_region)
  117. def del_temp_region():
  118. try:
  119. name = os.environ.pop('WIND_OVERRIDE')
  120. run_command("g.remove", quiet = True, region = name)
  121. except:
  122. pass
  123. # interface to g.findfile
  124. def find_file(name, element = 'cell'):
  125. lines = read_command("g.findfile", element = element, file = name).splitlines()
  126. return dict([_kv_regex.match(line).groups() for line in lines])
  127. # interface to g.list
  128. def list_grouped(type):
  129. dashes_re = re.compile("^----+$")
  130. mapset_re = re.compile("<(.*)>:$")
  131. result = {}
  132. mapset = None
  133. for line in read_command("g.list", type = type).splitlines():
  134. if line == "":
  135. continue
  136. if dashes_re.match(line):
  137. continue
  138. m = mapset_re.search(line)
  139. if m:
  140. mapset = m.group(1)
  141. result[mapset] = []
  142. continue
  143. if mapset:
  144. result[mapset].extend(line.split())
  145. return result
  146. def _concat(xs):
  147. result = []
  148. for x in xs:
  149. result.extend(x)
  150. return result
  151. def list_pairs(type):
  152. return _concat([[(map, mapset) for map in maps]
  153. for mapset, maps in list_grouped(type).iteritems()])
  154. def list_strings(type):
  155. return ["%s@%s" % pair for pair in list_pairs(type)]
  156. # color parsing
  157. named_colors = {
  158. "white": (1.00, 1.00, 1.00),
  159. "black": (0.00, 0.00, 0.00),
  160. "red": (1.00, 0.00, 0.00),
  161. "green": (0.00, 1.00, 0.00),
  162. "blue": (0.00, 0.00, 1.00),
  163. "yellow": (1.00, 1.00, 0.00),
  164. "magenta": (1.00, 0.00, 1.00),
  165. "cyan": (0.00, 1.00, 1.00),
  166. "aqua": (0.00, 0.75, 0.75),
  167. "grey": (0.75, 0.75, 0.75),
  168. "gray": (0.75, 0.75, 0.75),
  169. "orange": (1.00, 0.50, 0.00),
  170. "brown": (0.75, 0.50, 0.25),
  171. "purple": (0.50, 0.00, 1.00),
  172. "violet": (0.50, 0.00, 1.00),
  173. "indigo": (0.00, 0.50, 1.00)}
  174. def parse_color(val, dflt = None):
  175. if val in named_colors:
  176. return named_colors[val]
  177. vals = val.split(':')
  178. if len(vals) == 3:
  179. return tuple(float(v) / 255 for v in vals)
  180. return dflt