core.py 19 KB

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