core.py 17 KB

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