grass.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. # interface to g.message
  53. def message(msg, flag = None):
  54. run_command("g.message", flags = flag, message = msg)
  55. def debug(msg):
  56. message(msg, flag = 'd')
  57. def verbose(msg):
  58. message(msg, flag = 'v')
  59. def info(msg):
  60. message(msg, flag = 'i')
  61. def warning(msg):
  62. message(msg, flag = 'w')
  63. def error(msg):
  64. message(msg, flag = 'e')
  65. def fatal(msg):
  66. error(msg)
  67. sys.exit(1)
  68. # interface to g.parser
  69. def _parse_env():
  70. options = {}
  71. flags = {}
  72. for var, val in os.environ.iteritems():
  73. if var.startswith("GIS_OPT_"):
  74. opt = var.replace("GIS_OPT_", "", 1).lower()
  75. options[opt] = val;
  76. if var.startswith("GIS_FLAG_"):
  77. flg = var.replace("GIS_FLAG_", "", 1).lower()
  78. flags[flg] = bool(int(val));
  79. return (options, flags)
  80. def parser():
  81. if not os.getenv("GISBASE"):
  82. print >> sys.stderr, "You must be in GRASS GIS to run this program."
  83. sys.exit(1)
  84. if len(sys.argv) > 1 and sys.argv[1] == "@ARGS_PARSED@":
  85. return _parse_env()
  86. argv = sys.argv[:]
  87. name = argv[0]
  88. if not os.path.isabs(name):
  89. if os.sep in name or (os.altsep and os.altsep in name):
  90. argv[0] = os.path.abspath(name)
  91. else:
  92. argv[0] = os.path.join(sys.path[0], name)
  93. os.execvp("g.parser", [name] + argv)
  94. raise OSError("error executing g.parser")
  95. # interface to g.tempfile
  96. def tempfile():
  97. return read_command("g.tempfile", pid = os.getpid()).strip()
  98. # interface to g.gisenv
  99. _kv_regex = re.compile("([^=]+)='(.*)';?")
  100. def gisenv():
  101. lines = read_command("g.gisenv").splitlines()
  102. return dict([_kv_regex.match(line).groups() for line in lines])
  103. # interface to g.region
  104. def region():
  105. lines = read_command("g.region", flags='g').splitlines()
  106. return dict([line.split('=',1) for line in lines])
  107. def use_temp_region():
  108. name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
  109. run_command("g.region", save = name)
  110. os.environ['WIND_OVERRIDE'] = name
  111. atexit.register(del_temp_region)
  112. def del_temp_region():
  113. try:
  114. name = os.environ.pop('WIND_OVERRIDE')
  115. run_command("g.remove", quiet = True, region = name)
  116. except:
  117. pass
  118. # interface to g.findfile
  119. def find_file(name, element = 'cell'):
  120. lines = read_command("g.findfile", element = element, file = name).splitlines()
  121. return dict([_kv_regex.match(line).groups() for line in lines])
  122. # interface to g.list
  123. def list_grouped(type):
  124. dashes_re = re.compile("^----+$")
  125. mapset_re = re.compile("<(.*)>:$")
  126. result = {}
  127. for line in read_command("g.list", type = type).splitlines():
  128. if line == "":
  129. continue
  130. if dashes_re.match(line):
  131. continue
  132. m = mapset_re.search(line)
  133. if m:
  134. mapset = m.group(1)
  135. result[mapset] = []
  136. continue
  137. result[mapset].extend(line.split())
  138. return result
  139. def _concat(xs):
  140. result = []
  141. for x in xs:
  142. result.extend(x)
  143. return result
  144. def list_pairs(type):
  145. return _concat([[(map, mapset) for map in maps]
  146. for mapset, maps in list_grouped(type).iteritems()])
  147. def list_strings(type):
  148. return ["%s@%s" % pair for pair in list_pairs(type)]