core.py 19 KB

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