grass.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. import os
  2. import sys
  3. import types
  4. import subprocess
  5. import re
  6. import atexit
  7. import string
  8. # subprocess wrapper that uses shell on Windows
  9. class Popen(subprocess.Popen):
  10. def __init__(self, args, bufsize=0, executable=None,
  11. stdin=None, stdout=None, stderr=None,
  12. preexec_fn=None, close_fds=False, shell=None,
  13. cwd=None, env=None, universal_newlines=False,
  14. startupinfo=None, creationflags=0):
  15. if shell == None:
  16. shell = (sys.platform == "win32")
  17. subprocess.Popen.__init__(self, args, bufsize, executable,
  18. stdin, stdout, stderr,
  19. preexec_fn, close_fds, shell,
  20. cwd, env, universal_newlines,
  21. startupinfo, creationflags)
  22. PIPE = subprocess.PIPE
  23. STDOUT = subprocess.STDOUT
  24. def call(*args, **kwargs):
  25. return Popen(*args, **kwargs).wait()
  26. # GRASS-oriented interface to subprocess module
  27. _popen_args = ["bufsize", "executable", "stdin", "stdout", "stderr",
  28. "preexec_fn", "close_fds", "cwd", "env",
  29. "universal_newlines", "startupinfo", "creationflags"]
  30. def _make_val(val):
  31. if isinstance(val, types.StringType):
  32. return val
  33. if isinstance(val, types.ListType):
  34. return ",".join(map(_make_val, val))
  35. if isinstance(val, types.TupleType):
  36. return _make_val(list(val))
  37. return str(val)
  38. def make_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, **options):
  39. """Return a list of strings suitable for use as the args parameter to
  40. Popen() or call(). Example:
  41. >>> grass.make_command("g.message", flags = 'w', message = 'this is a warning')
  42. ['g.message', '-w', 'message=this is a warning']
  43. """
  44. args = [prog]
  45. if overwrite:
  46. args.append("--o")
  47. if quiet:
  48. args.append("--q")
  49. if verbose:
  50. args.append("--v")
  51. if flags:
  52. args.append("-%s" % flags)
  53. for opt, val in options.iteritems():
  54. if val != None:
  55. if opt[0] == '_':
  56. opt = opt[1:]
  57. args.append("%s=%s" % (opt, _make_val(val)))
  58. return args
  59. def start_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, **kwargs):
  60. """Returns a Popen object with the command created by make_command.
  61. Accepts any of the arguments which Popen() accepts apart from "args"
  62. and "shell".
  63. """
  64. options = {}
  65. popts = {}
  66. for opt, val in kwargs.iteritems():
  67. if opt in _popen_args:
  68. popts[opt] = val
  69. else:
  70. options[opt] = val
  71. args = make_command(prog, flags, overwrite, quiet, verbose, **options)
  72. return Popen(args, **popts)
  73. def run_command(*args, **kwargs):
  74. """Passes all arguments to start_command, then waits for the process to
  75. complete, returning its exit code. Similar to subprocess.call(), but
  76. with the make_command() interface.
  77. """
  78. ps = start_command(*args, **kwargs)
  79. return ps.wait()
  80. def pipe_command(*args, **kwargs):
  81. """Passes all arguments to start_command, but also adds
  82. "stdout = PIPE". Returns the Popen object.
  83. """
  84. kwargs['stdout'] = PIPE
  85. return start_command(*args, **kwargs)
  86. def feed_command(*args, **kwargs):
  87. """Passes all arguments to start_command, but also adds
  88. "stdin = PIPE". Returns the Popen object.
  89. """
  90. kwargs['stdin'] = PIPE
  91. return start_command(*args, **kwargs)
  92. def read_command(*args, **kwargs):
  93. """Passes all arguments to pipe_command, then waits for the process to
  94. complete, returning its stdout (i.e. similar to shell `backticks`).
  95. """
  96. ps = pipe_command(*args, **kwargs)
  97. return ps.communicate()[0]
  98. def write_command(*args, **kwargs):
  99. """Passes all arguments to feed_command, with the string specified
  100. by the 'stdin' argument fed to the process' stdin.
  101. """
  102. stdin = kwargs['stdin']
  103. p = feed_command(*args, **kwargs)
  104. p.stdin.write(stdin)
  105. p.stdin.close()
  106. return p.wait()
  107. def exec_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, env = None, **kwargs):
  108. """Interface to os.execvpe(), but with the make_command() interface."""
  109. args = make_command(prog, flags, overwrite, quiet, verbose, **kwargs)
  110. if env == None:
  111. env = os.environ
  112. os.execvpe(prog, args, env)
  113. # interface to g.message
  114. def message(msg, flag = None):
  115. """Display a message using g.message"""
  116. run_command("g.message", flags = flag, message = msg)
  117. def debug(msg):
  118. """Display a debugging message using g.message -d"""
  119. message(msg, flag = 'd')
  120. def verbose(msg):
  121. """Display a verbose message using g.message -v"""
  122. message(msg, flag = 'v')
  123. def info(msg):
  124. """Display an informational message using g.message -i"""
  125. message(msg, flag = 'i')
  126. def warning(msg):
  127. """Display a warning message using g.message -w"""
  128. message(msg, flag = 'w')
  129. def error(msg):
  130. """Display an error message using g.message -e"""
  131. message(msg, flag = 'e')
  132. def fatal(msg):
  133. """Display an error message using g.message -e, then abort"""
  134. error(msg)
  135. sys.exit(1)
  136. # interface to g.parser
  137. def _parse_env():
  138. options = {}
  139. flags = {}
  140. for var, val in os.environ.iteritems():
  141. if var.startswith("GIS_OPT_"):
  142. opt = var.replace("GIS_OPT_", "", 1).lower()
  143. options[opt] = val;
  144. if var.startswith("GIS_FLAG_"):
  145. flg = var.replace("GIS_FLAG_", "", 1).lower()
  146. flags[flg] = bool(int(val));
  147. return (options, flags)
  148. def parser():
  149. """Interface to g.parser, intended to be run from the top-level, e.g.:
  150. if __name__ == "__main__":
  151. options, flags = grass.parser()
  152. main()
  153. Thereafter, the global variables "options" and "flags" will be
  154. dictionaries containing option/flag values, keyed by lower-case
  155. option/flag names. The values in "options" are strings, those in
  156. "flags" are Python booleans.
  157. """
  158. if not os.getenv("GISBASE"):
  159. print >> sys.stderr, "You must be in GRASS GIS to run this program."
  160. sys.exit(1)
  161. if len(sys.argv) > 1 and sys.argv[1] == "@ARGS_PARSED@":
  162. return _parse_env()
  163. cmdline = [basename(sys.argv[0])]
  164. cmdline += ['"' + arg + '"' for arg in sys.argv[1:]]
  165. os.environ['CMDLINE'] = ' '.join(cmdline)
  166. argv = sys.argv[:]
  167. name = argv[0]
  168. if not os.path.isabs(name):
  169. if os.sep in name or (os.altsep and os.altsep in name):
  170. argv[0] = os.path.abspath(name)
  171. else:
  172. argv[0] = os.path.join(sys.path[0], name)
  173. os.execvp("g.parser", [name] + argv)
  174. raise OSError("error executing g.parser")
  175. # interface to g.tempfile
  176. def tempfile():
  177. """Returns the name of a temporary file, created with g.tempfile."""
  178. return read_command("g.tempfile", pid = os.getpid()).strip()
  179. # key-value parsers
  180. def parse_key_val(s, sep = '=', dflt = None):
  181. """Parse a string into a dictionary, where entries are separated
  182. by newlines and the key and value are separated by `sep' (default: `=')
  183. """
  184. result = {}
  185. for line in s.splitlines():
  186. kv = line.split(sep, 1)
  187. k = kv[0].strip()
  188. if len(kv) > 1:
  189. v = kv[1]
  190. else:
  191. v = dflt
  192. result[k] = v
  193. return result
  194. # interface to g.gisenv
  195. def gisenv():
  196. """Returns the output from running g.gisenv (with no arguments), as a
  197. dictionary.
  198. """
  199. s = read_command("g.gisenv", flags='n')
  200. return parse_key_val(s)
  201. # interface to g.region
  202. def region():
  203. """Returns the output from running "g.region -g", as a dictionary."""
  204. s = read_command("g.region", flags='g')
  205. return parse_key_val(s)
  206. def use_temp_region():
  207. """Copies the current region to a temporary region with "g.region save=",
  208. then sets WIND_OVERRIDE to refer to that region. Installs an atexit
  209. handler to delete the temporary region upon termination.
  210. """
  211. name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
  212. run_command("g.region", save = name)
  213. os.environ['WIND_OVERRIDE'] = name
  214. atexit.register(del_temp_region)
  215. def del_temp_region():
  216. """Unsets WIND_OVERRIDE and removes any region named by it."""
  217. try:
  218. name = os.environ.pop('WIND_OVERRIDE')
  219. run_command("g.remove", quiet = True, region = name)
  220. except:
  221. pass
  222. # interface to g.findfile
  223. def find_file(name, element = 'cell', mapset = None):
  224. """Returns the output from running g.findfile as a dictionary."""
  225. s = read_command("g.findfile", flags='n', element = element, file = name, mapset = mapset)
  226. return parse_key_val(s)
  227. # interface to g.list
  228. def list_grouped(type):
  229. """Returns the output from running g.list, as a dictionary where the keys
  230. are mapset names and the values are lists of maps in that mapset.
  231. """
  232. dashes_re = re.compile("^----+$")
  233. mapset_re = re.compile("<(.*)>:$")
  234. result = {}
  235. mapset = None
  236. for line in read_command("g.list", type = type).splitlines():
  237. if line == "":
  238. continue
  239. if dashes_re.match(line):
  240. continue
  241. m = mapset_re.search(line)
  242. if m:
  243. mapset = m.group(1)
  244. result[mapset] = []
  245. continue
  246. if mapset:
  247. result[mapset].extend(line.split())
  248. return result
  249. def _concat(xs):
  250. result = []
  251. for x in xs:
  252. result.extend(x)
  253. return result
  254. def list_pairs(type):
  255. """Returns the output from running g.list, as a list of (map, mapset)
  256. pairs.
  257. """
  258. return _concat([[(map, mapset) for map in maps]
  259. for mapset, maps in list_grouped(type).iteritems()])
  260. def list_strings(type):
  261. """Returns the output from running g.list, as a list of qualified names."""
  262. return ["%s@%s" % pair for pair in list_pairs(type)]
  263. # color parsing
  264. named_colors = {
  265. "white": (1.00, 1.00, 1.00),
  266. "black": (0.00, 0.00, 0.00),
  267. "red": (1.00, 0.00, 0.00),
  268. "green": (0.00, 1.00, 0.00),
  269. "blue": (0.00, 0.00, 1.00),
  270. "yellow": (1.00, 1.00, 0.00),
  271. "magenta": (1.00, 0.00, 1.00),
  272. "cyan": (0.00, 1.00, 1.00),
  273. "aqua": (0.00, 0.75, 0.75),
  274. "grey": (0.75, 0.75, 0.75),
  275. "gray": (0.75, 0.75, 0.75),
  276. "orange": (1.00, 0.50, 0.00),
  277. "brown": (0.75, 0.50, 0.25),
  278. "purple": (0.50, 0.00, 1.00),
  279. "violet": (0.50, 0.00, 1.00),
  280. "indigo": (0.00, 0.50, 1.00)}
  281. def parse_color(val, dflt = None):
  282. """Parses the string "val" as a GRASS colour, which can be either one of
  283. the named colours or an R:G:B tuple e.g. 255:255:255. Returns an
  284. (r,g,b) triple whose components are floating point values between 0
  285. and 1.
  286. """
  287. if val in named_colors:
  288. return named_colors[val]
  289. vals = val.split(':')
  290. if len(vals) == 3:
  291. return tuple(float(v) / 255 for v in vals)
  292. return dflt
  293. # check GRASS_OVERWRITE
  294. def overwrite():
  295. """Return True if existing files may be overwritten"""
  296. owstr = 'GRASS_OVERWRITE'
  297. return owstr in os.environ and os.environ[owstr] != '0'
  298. # check GRASS_VERBOSE
  299. def verbosity():
  300. """Return the verbosity level selected by GRASS_VERBOSE"""
  301. vbstr = os.getenv('GRASS_VERBOSE')
  302. if vbstr:
  303. return int(vbstr)
  304. else:
  305. return 0
  306. ## various utilities, not specific to GRASS
  307. # basename inc. extension stripping
  308. def basename(path, ext = None):
  309. """Remove leading directory components and an optional extension
  310. from the specified path
  311. """
  312. name = os.path.basename(path)
  313. if not ext:
  314. return name
  315. fs = name.rsplit('.', 1)
  316. if len(fs) > 1 and fs[1].lower() == ext:
  317. name = fs[0]
  318. return name
  319. # find a program (replacement for "which")
  320. def find_program(pgm, args = []):
  321. """Attempt to run a program, with optional arguments. Return False
  322. if the attempt failed due to a missing executable, True otherwise
  323. """
  324. nuldev = file(os.devnull, 'w+')
  325. try:
  326. call([pgm] + args, stdin = nuldev, stdout = nuldev, stderr = nuldev)
  327. found = True
  328. except:
  329. found = False
  330. nuldev.close()
  331. return found
  332. # try to remove a file, without complaints
  333. def try_remove(path):
  334. """Attempt to remove a file; no exception is generated if the
  335. attempt fails.
  336. """
  337. try:
  338. os.remove(path)
  339. except:
  340. pass
  341. # try to remove a directory, without complaints
  342. def try_rmdir(path):
  343. """Attempt to remove a directory; no exception is generated if the
  344. attempt fails.
  345. """
  346. try:
  347. os.rmdir(path)
  348. except:
  349. pass
  350. # run "v.db.connect -g ..." and parse output
  351. def vector_db(map, layer = None, **args):
  352. """Return the database connection details for a vector map
  353. (interface to `v.db.connect -g').
  354. """
  355. s = read_command('v.db.connect', flags = 'g', map = map, layer = layer, fs = '|', **args)
  356. result = []
  357. for l in s.splitlines():
  358. f = l.split('|')
  359. if len(f) != 5:
  360. continue
  361. if layer and int(layer) == int(f[0]):
  362. return f
  363. result.append(f)
  364. if not layer:
  365. return result
  366. # run "db.describe -c ..." and parse output
  367. def db_describe(table, **args):
  368. """Return the list of columns for a database table
  369. (interface to `db.describe -c').
  370. """
  371. s = read_command('db.describe', flags = 'c', table = table, **args)
  372. if not s:
  373. return None
  374. cols = []
  375. result = {}
  376. for l in s.splitlines():
  377. f = l.split(':')
  378. key = f[0]
  379. f[1] = f[1].lstrip(' ')
  380. if key.startswith('Column '):
  381. n = int(key.split(' ')[1])
  382. cols.insert(n, f[1:])
  383. elif key in ['ncols', 'nrows']:
  384. result[key] = int(f[1])
  385. else:
  386. result[key] = f[1:]
  387. result['cols'] = cols
  388. return result
  389. # run "db.connect -p" and parse output
  390. def db_connection():
  391. """Return the current database connection parameters
  392. (interface to `db.connect -p').
  393. """
  394. s = read_command('db.connect', flags = 'p')
  395. return parse_key_val(s, sep = ':')
  396. # run "v.info -c ..." and parse output
  397. def vector_columns(map, layer = None, **args):
  398. """Return the list of columns for the database table connected to
  399. a vector map (interface to `v.info -c').
  400. """
  401. s = read_command('v.info', flags = 'c', map = map, layer = layer, quiet = True, **args)
  402. result = []
  403. for line in s.splitlines():
  404. f = line.split('|')
  405. if len(f) == 2:
  406. result.append(f)
  407. return result
  408. # add vector history
  409. def vector_history(map):
  410. """Set the command history for a vector map to the command used to
  411. invoke the script (interface to `v.support').
  412. """
  413. run_command('v.support', map = map, cmdhist = os.environ['CMDLINE'])
  414. # add raster history
  415. def raster_history(map):
  416. """Set the command history for a raster map to the command used to
  417. invoke the script (interface to `r.support').
  418. """
  419. run_command('r.support', map = map, history = os.environ['CMDLINE'])
  420. # run "r.info -rgstmpud ..." and parse output
  421. def raster_info(map):
  422. """Return information about a raster map (interface to `r.info')."""
  423. s = read_command('r.info', flags = 'rgstmpud', map = map)
  424. kv = parse_key_val(s)
  425. for k in ['min', 'max', 'north', 'south', 'east', 'west', 'nsres', 'ewres']:
  426. kv[k] = float(kv[k])
  427. return kv
  428. # interface to r.mapcalc
  429. def mapcalc(exp, **kwargs):
  430. t = string.Template(exp)
  431. e = t.substitute(**kwargs)
  432. if run_command('r.mapcalc', expression = e) != 0:
  433. grass.fatal("An error occurred while running r.mapcalc")