grass.py 17 KB

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