grass.py 7.5 KB

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