grass.py 4.5 KB

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