core.py 19 KB

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