grass.py 7.4 KB

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