grass.py 15 KB

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