grass.py 14 KB

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