grass.py 17 KB

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