grass.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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 list_grouped2(type, pattern=None):
  250. """Returns the output from running g.mlist, as a dictionary where the keys
  251. are mapset names and the values are lists of maps in that mapset.
  252. """
  253. result = {}
  254. mapset = None
  255. for line in read_command("g.mlist", flags="m",
  256. type = type, pattern = pattern).splitlines():
  257. try:
  258. map, mapset = line.split('@')
  259. except ValueError:
  260. print >> sys.stderr, "Invalid element '%s'" % line
  261. continue
  262. if result.has_key(mapset):
  263. result[mapset].append(map)
  264. else:
  265. result[mapset] = [map, ]
  266. return result
  267. def _concat(xs):
  268. result = []
  269. for x in xs:
  270. result.extend(x)
  271. return result
  272. def list_pairs(type):
  273. """Returns the output from running g.list, as a list of (map, mapset)
  274. pairs.
  275. """
  276. return _concat([[(map, mapset) for map in maps]
  277. for mapset, maps in list_grouped(type).iteritems()])
  278. def list_strings(type):
  279. """Returns the output from running g.list, as a list of qualified names."""
  280. return ["%s@%s" % pair for pair in list_pairs(type)]
  281. # color parsing
  282. named_colors = {
  283. "white": (1.00, 1.00, 1.00),
  284. "black": (0.00, 0.00, 0.00),
  285. "red": (1.00, 0.00, 0.00),
  286. "green": (0.00, 1.00, 0.00),
  287. "blue": (0.00, 0.00, 1.00),
  288. "yellow": (1.00, 1.00, 0.00),
  289. "magenta": (1.00, 0.00, 1.00),
  290. "cyan": (0.00, 1.00, 1.00),
  291. "aqua": (0.00, 0.75, 0.75),
  292. "grey": (0.75, 0.75, 0.75),
  293. "gray": (0.75, 0.75, 0.75),
  294. "orange": (1.00, 0.50, 0.00),
  295. "brown": (0.75, 0.50, 0.25),
  296. "purple": (0.50, 0.00, 1.00),
  297. "violet": (0.50, 0.00, 1.00),
  298. "indigo": (0.00, 0.50, 1.00)}
  299. def parse_color(val, dflt = None):
  300. """Parses the string "val" as a GRASS colour, which can be either one of
  301. the named colours or an R:G:B tuple e.g. 255:255:255. Returns an
  302. (r,g,b) triple whose components are floating point values between 0
  303. and 1.
  304. """
  305. if val in named_colors:
  306. return named_colors[val]
  307. vals = val.split(':')
  308. if len(vals) == 3:
  309. return tuple(float(v) / 255 for v in vals)
  310. return dflt
  311. # check GRASS_OVERWRITE
  312. def overwrite():
  313. """Return True if existing files may be overwritten"""
  314. owstr = 'GRASS_OVERWRITE'
  315. return owstr in os.environ and os.environ[owstr] != '0'
  316. # check GRASS_VERBOSE
  317. def verbosity():
  318. """Return the verbosity level selected by GRASS_VERBOSE"""
  319. vbstr = os.getenv('GRASS_VERBOSE')
  320. if vbstr:
  321. return int(vbstr)
  322. else:
  323. return 0
  324. ## various utilities, not specific to GRASS
  325. # basename inc. extension stripping
  326. def basename(path, ext = None):
  327. """Remove leading directory components and an optional extension
  328. from the specified path
  329. """
  330. name = os.path.basename(path)
  331. if not ext:
  332. return name
  333. fs = name.rsplit('.', 1)
  334. if len(fs) > 1 and fs[1].lower() == ext:
  335. name = fs[0]
  336. return name
  337. # find a program (replacement for "which")
  338. def find_program(pgm, args = []):
  339. """Attempt to run a program, with optional arguments. Return False
  340. if the attempt failed due to a missing executable, True otherwise
  341. """
  342. nuldev = file(os.devnull, 'w+')
  343. try:
  344. call([pgm] + args, stdin = nuldev, stdout = nuldev, stderr = nuldev)
  345. found = True
  346. except:
  347. found = False
  348. nuldev.close()
  349. return found
  350. # try to remove a file, without complaints
  351. def try_remove(path):
  352. """Attempt to remove a file; no exception is generated if the
  353. attempt fails.
  354. """
  355. try:
  356. os.remove(path)
  357. except:
  358. pass
  359. # try to remove a directory, without complaints
  360. def try_rmdir(path):
  361. """Attempt to remove a directory; no exception is generated if the
  362. attempt fails.
  363. """
  364. try:
  365. os.rmdir(path)
  366. except:
  367. pass
  368. # run "v.db.connect -g ..." and parse output
  369. def vector_db(map, layer = None, **args):
  370. """Return the database connection details for a vector map
  371. (interface to `v.db.connect -g').
  372. """
  373. s = read_command('v.db.connect', flags = 'g', map = map, layer = layer, fs = '|', **args)
  374. result = []
  375. for l in s.splitlines():
  376. f = l.split('|')
  377. if len(f) != 5:
  378. continue
  379. if layer and int(layer) == int(f[0]):
  380. return f
  381. result.append(f)
  382. if not layer:
  383. return result
  384. # run "db.describe -c ..." and parse output
  385. def db_describe(table, **args):
  386. """Return the list of columns for a database table
  387. (interface to `db.describe -c').
  388. """
  389. s = read_command('db.describe', flags = 'c', table = table, **args)
  390. if not s:
  391. return None
  392. cols = []
  393. result = {}
  394. for l in s.splitlines():
  395. f = l.split(':')
  396. key = f[0]
  397. f[1] = f[1].lstrip(' ')
  398. if key.startswith('Column '):
  399. n = int(key.split(' ')[1])
  400. cols.insert(n, f[1:])
  401. elif key in ['ncols', 'nrows']:
  402. result[key] = int(f[1])
  403. else:
  404. result[key] = f[1:]
  405. result['cols'] = cols
  406. return result
  407. # run "db.connect -p" and parse output
  408. def db_connection():
  409. """Return the current database connection parameters
  410. (interface to `db.connect -p').
  411. """
  412. s = read_command('db.connect', flags = 'p')
  413. return parse_key_val(s, sep = ':')
  414. # run "v.info -c ..." and parse output
  415. def vector_columns(map, layer = None, **args):
  416. """Return the directory of columns for the database table connected to
  417. a vector map (interface to `v.info -c').
  418. """
  419. s = read_command('v.info', flags = 'c', map = map, layer = layer, quiet = True, **args)
  420. result = {}
  421. for line in s.splitlines():
  422. f = line.split('|')
  423. if len(f) == 2:
  424. result[f[1]] = f[0]
  425. return result
  426. # add vector history
  427. def vector_history(map):
  428. """Set the command history for a vector map to the command used to
  429. invoke the script (interface to `v.support').
  430. """
  431. run_command('v.support', map = map, cmdhist = os.environ['CMDLINE'])
  432. # add raster history
  433. def raster_history(map):
  434. """Set the command history for a raster map to the command used to
  435. invoke the script (interface to `r.support').
  436. """
  437. run_command('r.support', map = map, history = os.environ['CMDLINE'])
  438. # run "r.info -rgstmpud ..." and parse output
  439. def raster_info(map):
  440. """Return information about a raster map (interface to `r.info')."""
  441. s = read_command('r.info', flags = 'rgstmpud', map = map)
  442. kv = parse_key_val(s)
  443. for k in ['min', 'max', 'north', 'south', 'east', 'west', 'nsres', 'ewres']:
  444. kv[k] = float(kv[k])
  445. return kv
  446. # interface to r.mapcalc
  447. def mapcalc(exp, **kwargs):
  448. t = string.Template(exp)
  449. e = t.substitute(**kwargs)
  450. if run_command('r.mapcalc', expression = e) != 0:
  451. grass.fatal("An error occurred while running r.mapcalc")