grass.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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, val_type = 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. if val_type:
  193. result[k] = val_type(v)
  194. else:
  195. result[k] = v
  196. return result
  197. # interface to g.gisenv
  198. def gisenv():
  199. """Returns the output from running g.gisenv (with no arguments), as a
  200. dictionary.
  201. """
  202. s = read_command("g.gisenv", flags='n')
  203. return parse_key_val(s)
  204. # interface to g.region
  205. def region():
  206. """Returns the output from running "g.region -g", as a dictionary."""
  207. s = read_command("g.region", flags='g')
  208. return parse_key_val(s)
  209. def use_temp_region():
  210. """Copies the current region to a temporary region with "g.region save=",
  211. then sets WIND_OVERRIDE to refer to that region. Installs an atexit
  212. handler to delete the temporary region upon termination.
  213. """
  214. name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
  215. run_command("g.region", save = name)
  216. os.environ['WIND_OVERRIDE'] = name
  217. atexit.register(del_temp_region)
  218. def del_temp_region():
  219. """Unsets WIND_OVERRIDE and removes any region named by it."""
  220. try:
  221. name = os.environ.pop('WIND_OVERRIDE')
  222. run_command("g.remove", quiet = True, region = name)
  223. except:
  224. pass
  225. # interface to g.findfile
  226. def find_file(name, element = 'cell', mapset = None):
  227. """Returns the output from running g.findfile as a dictionary."""
  228. s = read_command("g.findfile", flags='n', element = element, file = name, mapset = mapset)
  229. return parse_key_val(s)
  230. # interface to g.list
  231. def list_grouped(type):
  232. """Returns the output from running g.list, as a dictionary where the keys
  233. are mapset names and the values are lists of maps in that mapset.
  234. """
  235. dashes_re = re.compile("^----+$")
  236. mapset_re = re.compile("<(.*)>")
  237. result = {}
  238. mapset = None
  239. for line in read_command("g.list", type = type).splitlines():
  240. if line == "":
  241. continue
  242. if dashes_re.match(line):
  243. continue
  244. m = mapset_re.search(line)
  245. if m:
  246. mapset = m.group(1)
  247. result[mapset] = []
  248. continue
  249. if mapset:
  250. result[mapset].extend(line.split())
  251. return result
  252. def mlist_grouped(type, mapset = None, pattern = None):
  253. """Returns the output from running g.mlist, as a dictionary where the keys
  254. are mapset names and the values are lists of maps in that mapset.
  255. """
  256. result = {}
  257. mapset_element = None
  258. for line in read_command("g.mlist", flags="m",
  259. type = type, mapset = mapset, pattern = pattern).splitlines():
  260. try:
  261. map, mapset_element = line.split('@')
  262. except ValueError:
  263. print >> sys.stderr, "Invalid element '%s'" % line
  264. continue
  265. if result.has_key(mapset_element):
  266. result[mapset_element].append(map)
  267. else:
  268. result[mapset_element] = [map, ]
  269. return result
  270. def _concat(xs):
  271. result = []
  272. for x in xs:
  273. result.extend(x)
  274. return result
  275. def list_pairs(type):
  276. """Returns the output from running g.list, as a list of (map, mapset)
  277. pairs.
  278. """
  279. return _concat([[(map, mapset) for map in maps]
  280. for mapset, maps in list_grouped(type).iteritems()])
  281. def list_strings(type):
  282. """Returns the output from running g.list, as a list of qualified names."""
  283. return ["%s@%s" % pair for pair in list_pairs(type)]
  284. # color parsing
  285. named_colors = {
  286. "white": (1.00, 1.00, 1.00),
  287. "black": (0.00, 0.00, 0.00),
  288. "red": (1.00, 0.00, 0.00),
  289. "green": (0.00, 1.00, 0.00),
  290. "blue": (0.00, 0.00, 1.00),
  291. "yellow": (1.00, 1.00, 0.00),
  292. "magenta": (1.00, 0.00, 1.00),
  293. "cyan": (0.00, 1.00, 1.00),
  294. "aqua": (0.00, 0.75, 0.75),
  295. "grey": (0.75, 0.75, 0.75),
  296. "gray": (0.75, 0.75, 0.75),
  297. "orange": (1.00, 0.50, 0.00),
  298. "brown": (0.75, 0.50, 0.25),
  299. "purple": (0.50, 0.00, 1.00),
  300. "violet": (0.50, 0.00, 1.00),
  301. "indigo": (0.00, 0.50, 1.00)}
  302. def parse_color(val, dflt = None):
  303. """Parses the string "val" as a GRASS colour, which can be either one of
  304. the named colours or an R:G:B tuple e.g. 255:255:255. Returns an
  305. (r,g,b) triple whose components are floating point values between 0
  306. and 1.
  307. """
  308. if val in named_colors:
  309. return named_colors[val]
  310. vals = val.split(':')
  311. if len(vals) == 3:
  312. return tuple(float(v) / 255 for v in vals)
  313. return dflt
  314. # check GRASS_OVERWRITE
  315. def overwrite():
  316. """Return True if existing files may be overwritten"""
  317. owstr = 'GRASS_OVERWRITE'
  318. return owstr in os.environ and os.environ[owstr] != '0'
  319. # check GRASS_VERBOSE
  320. def verbosity():
  321. """Return the verbosity level selected by GRASS_VERBOSE"""
  322. vbstr = os.getenv('GRASS_VERBOSE')
  323. if vbstr:
  324. return int(vbstr)
  325. else:
  326. return 0
  327. ## various utilities, not specific to GRASS
  328. # basename inc. extension stripping
  329. def basename(path, ext = None):
  330. """Remove leading directory components and an optional extension
  331. from the specified path
  332. """
  333. name = os.path.basename(path)
  334. if not ext:
  335. return name
  336. fs = name.rsplit('.', 1)
  337. if len(fs) > 1 and fs[1].lower() == ext:
  338. name = fs[0]
  339. return name
  340. # find a program (replacement for "which")
  341. def find_program(pgm, args = []):
  342. """Attempt to run a program, with optional arguments. Return False
  343. if the attempt failed due to a missing executable, True otherwise
  344. """
  345. nuldev = file(os.devnull, 'w+')
  346. try:
  347. call([pgm] + args, stdin = nuldev, stdout = nuldev, stderr = nuldev)
  348. found = True
  349. except:
  350. found = False
  351. nuldev.close()
  352. return found
  353. # try to remove a file, without complaints
  354. def try_remove(path):
  355. """Attempt to remove a file; no exception is generated if the
  356. attempt fails.
  357. """
  358. try:
  359. os.remove(path)
  360. except:
  361. pass
  362. # try to remove a directory, without complaints
  363. def try_rmdir(path):
  364. """Attempt to remove a directory; no exception is generated if the
  365. attempt fails.
  366. """
  367. try:
  368. os.rmdir(path)
  369. except:
  370. pass
  371. # run "v.db.connect -g ..." and parse output
  372. def vector_db(map, **args):
  373. """Return the database connection details for a vector map
  374. (interface to `v.db.connect -g').
  375. @param map vector map
  376. @return dictionary { layer : { 'layer', 'table, 'database', 'driver', 'key' }
  377. """
  378. s = read_command('v.db.connect', flags = 'g', map = map, fs = ';', **args)
  379. result = {}
  380. for l in s.splitlines():
  381. f = l.split(';')
  382. if len(f) != 5:
  383. continue
  384. if '/' in f[0]:
  385. f1 = f[0].split('/')
  386. layer = f1[0]
  387. name = f1[1]
  388. else:
  389. layer = f[0]
  390. name = ''
  391. result[int(layer)] = {
  392. 'layer' : layer,
  393. 'name' : name,
  394. 'table' : f[1],
  395. 'key' : f[2],
  396. 'database' : f[3],
  397. 'driver' : f[4] }
  398. return result
  399. def vector_layer_db(map, layer):
  400. """Return the database connection details for a vector map layer.
  401. If db connection for given layer is not defined, fatal() is called."""
  402. try:
  403. f = vector_db(map)[int(layer)]
  404. except KeyError:
  405. grass.fatal("Database connection not defined for layer %s" % layer)
  406. return f
  407. # run "db.describe -c ..." and parse output
  408. def db_describe(table, **args):
  409. """Return the list of columns for a database table
  410. (interface to `db.describe -c').
  411. """
  412. s = read_command('db.describe', flags = 'c', table = table, **args)
  413. if not s:
  414. return None
  415. cols = []
  416. result = {}
  417. for l in s.splitlines():
  418. f = l.split(':')
  419. key = f[0]
  420. f[1] = f[1].lstrip(' ')
  421. if key.startswith('Column '):
  422. n = int(key.split(' ')[1])
  423. cols.insert(n, f[1:])
  424. elif key in ['ncols', 'nrows']:
  425. result[key] = int(f[1])
  426. else:
  427. result[key] = f[1:]
  428. result['cols'] = cols
  429. return result
  430. # run "db.connect -p" and parse output
  431. def db_connection():
  432. """Return the current database connection parameters
  433. (interface to `db.connect -p').
  434. """
  435. s = read_command('db.connect', flags = 'p')
  436. return parse_key_val(s, sep = ':')
  437. # run "v.info -c ..." and parse output
  438. def vector_columns(map, layer = None, **args):
  439. """Return a dictionary of the columns for the database table connected to
  440. a vector map (interface to `v.info -c').
  441. """
  442. s = read_command('v.info', flags = 'c', map = map, layer = layer, quiet = True, **args)
  443. result = {}
  444. for line in s.splitlines():
  445. f = line.split('|')
  446. if len(f) == 2:
  447. result[f[1]] = f[0]
  448. return result
  449. # add vector history
  450. def vector_history(map):
  451. """Set the command history for a vector map to the command used to
  452. invoke the script (interface to `v.support').
  453. """
  454. run_command('v.support', map = map, cmdhist = os.environ['CMDLINE'])
  455. # run "v.info -t" and parse output
  456. def vector_info_topo(map):
  457. """Return information about a vector map (interface to `v.info -t')."""
  458. s = read_command('v.info', flags = 't', map = map)
  459. return parse_key_val(s, val_type = int)
  460. # add raster history
  461. def raster_history(map):
  462. """Set the command history for a raster map to the command used to
  463. invoke the script (interface to `r.support').
  464. @return True on success
  465. @return False on failure
  466. """
  467. current_mapset = gisenv()['MAPSET']
  468. if find_file(name = map)['mapset'] == current_mapset:
  469. run_command('r.support', map = map, history = os.environ['CMDLINE'])
  470. return True
  471. warning("Unable to write history for <%s>. Raster map <%s> not found in current mapset." % (map, map))
  472. return False
  473. # run "r.info -rgstmpud ..." and parse output
  474. def raster_info(map):
  475. """Return information about a raster map (interface to `r.info')."""
  476. s = read_command('r.info', flags = 'rgstmpud', map = map)
  477. kv = parse_key_val(s)
  478. for k in ['min', 'max', 'north', 'south', 'east', 'west', 'nsres', 'ewres']:
  479. kv[k] = float(kv[k])
  480. return kv
  481. # interface to r.mapcalc
  482. def mapcalc(exp, **kwargs):
  483. t = string.Template(exp)
  484. e = t.substitute(**kwargs)
  485. if run_command('r.mapcalc', expression = e) != 0:
  486. fatal("An error occurred while running r.mapcalc")