core.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  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_env():
  262. options = {}
  263. flags = {}
  264. for var, val in os.environ.iteritems():
  265. if var.startswith("GIS_OPT_"):
  266. opt = var.replace("GIS_OPT_", "", 1).lower()
  267. options[opt] = val;
  268. if var.startswith("GIS_FLAG_"):
  269. flg = var.replace("GIS_FLAG_", "", 1).lower()
  270. flags[flg] = bool(int(val));
  271. return (options, flags)
  272. def parser():
  273. """!Interface to g.parser, intended to be run from the top-level, e.g.:
  274. @code
  275. if __name__ == "__main__":
  276. options, flags = grass.parser()
  277. main()
  278. @endcode
  279. Thereafter, the global variables "options" and "flags" will be
  280. dictionaries containing option/flag values, keyed by lower-case
  281. option/flag names. The values in "options" are strings, those in
  282. "flags" are Python booleans.
  283. """
  284. if not os.getenv("GISBASE"):
  285. print >> sys.stderr, "You must be in GRASS GIS to run this program."
  286. sys.exit(1)
  287. if len(sys.argv) > 1 and sys.argv[1] == "@ARGS_PARSED@":
  288. return _parse_env()
  289. cmdline = [basename(sys.argv[0])]
  290. cmdline += ['"' + arg + '"' for arg in sys.argv[1:]]
  291. os.environ['CMDLINE'] = ' '.join(cmdline)
  292. argv = sys.argv[:]
  293. name = argv[0]
  294. if not os.path.isabs(name):
  295. if os.sep in name or (os.altsep and os.altsep in name):
  296. argv[0] = os.path.abspath(name)
  297. else:
  298. argv[0] = os.path.join(sys.path[0], name)
  299. if sys.platform == "win32":
  300. os.execvp("g.parser.exe", [name] + argv)
  301. else:
  302. os.execvp("g.parser", [name] + argv)
  303. raise OSError("error executing g.parser")
  304. # interface to g.tempfile
  305. def tempfile():
  306. """!Returns the name of a temporary file, created with g.tempfile."""
  307. return read_command("g.tempfile", pid = os.getpid()).strip()
  308. # key-value parsers
  309. def parse_key_val(s, sep = '=', dflt = None, val_type = None, vsep = None):
  310. """!Parse a string into a dictionary, where entries are separated
  311. by newlines and the key and value are separated by `sep' (default: `=')
  312. @param s string to be parsed
  313. @param sep key/value separator
  314. @param dflt default value to be used
  315. @param val_type value type (None for no cast)
  316. @param vsep vertical separator (default os.linesep)
  317. @return parsed input (dictionary of keys/values)
  318. """
  319. result = {}
  320. if not s:
  321. return result
  322. if vsep:
  323. lines = s.split(vsep)
  324. try:
  325. lines.remove('\n')
  326. except ValueError:
  327. pass
  328. else:
  329. lines = s.splitlines()
  330. for line in lines:
  331. kv = line.split(sep, 1)
  332. k = kv[0].strip()
  333. if len(kv) > 1:
  334. v = kv[1]
  335. else:
  336. v = dflt
  337. if val_type:
  338. result[k] = val_type(v)
  339. else:
  340. result[k] = v
  341. return result
  342. # interface to g.gisenv
  343. def gisenv():
  344. """!Returns the output from running g.gisenv (with no arguments), as a
  345. dictionary. Example:
  346. \code
  347. >>> env = grass.gisenv()
  348. >>> print env['GISDBASE']
  349. /opt/grass-data
  350. \endcode
  351. @return list of GRASS variables
  352. """
  353. s = read_command("g.gisenv", flags='n')
  354. return parse_key_val(s)
  355. # interface to g.region
  356. def region():
  357. """!Returns the output from running "g.region -g", as a
  358. dictionary. Example:
  359. \code
  360. >>> region = grass.region()
  361. >>> [region[key] for key in "nsew"]
  362. ['4928000', '4914020', '609000', '590010']
  363. >>> (region['nsres'], region['ewres'])
  364. ('30', '30')
  365. \endcode
  366. @return dictionary of region values
  367. """
  368. s = read_command("g.region", flags='g')
  369. return parse_key_val(s, val_type = float)
  370. def use_temp_region():
  371. """!Copies the current region to a temporary region with "g.region save=",
  372. then sets WIND_OVERRIDE to refer to that region. Installs an atexit
  373. handler to delete the temporary region upon termination.
  374. """
  375. name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
  376. run_command("g.region", save = name)
  377. os.environ['WIND_OVERRIDE'] = name
  378. atexit.register(del_temp_region)
  379. def del_temp_region():
  380. """!Unsets WIND_OVERRIDE and removes any region named by it."""
  381. try:
  382. name = os.environ.pop('WIND_OVERRIDE')
  383. run_command("g.remove", quiet = True, region = name)
  384. except:
  385. pass
  386. # interface to g.findfile
  387. def find_file(name, element = 'cell', mapset = None):
  388. """!Returns the output from running g.findfile as a
  389. dictionary. Example:
  390. \code
  391. >>> result = grass.find_file('fields', element = 'vector')
  392. >>> print result['fullname']
  393. fields@PERMANENT
  394. >>> print result['file']
  395. /opt/grass-data/spearfish60/PERMANENT/vector/fields
  396. \endcode
  397. @param name file name
  398. @param element element type (default 'cell')
  399. @param mapset mapset name (default all mapsets in search path)
  400. @return parsed output of g.findfile
  401. """
  402. s = read_command("g.findfile", flags='n', element = element, file = name, mapset = mapset)
  403. return parse_key_val(s)
  404. # interface to g.list
  405. def list_grouped(type):
  406. """!Returns the output from running g.list, as a dictionary where the keys
  407. are mapset names and the values are lists of maps in that mapset. Example:
  408. \code
  409. >>> grass.list_grouped('rast')['PERMANENT']
  410. ['aspect', 'erosion1', 'quads', 'soils', 'strm.dist', ...
  411. \endcode
  412. @param type element type
  413. """
  414. dashes_re = re.compile("^----+$")
  415. mapset_re = re.compile("<(.*)>")
  416. result = {}
  417. mapset = None
  418. for line in read_command("g.list", type = type).splitlines():
  419. if line == "":
  420. continue
  421. if dashes_re.match(line):
  422. continue
  423. m = mapset_re.search(line)
  424. if m:
  425. mapset = m.group(1)
  426. result[mapset] = []
  427. continue
  428. if mapset:
  429. result[mapset].extend(line.split())
  430. return result
  431. def mlist_grouped(type, mapset = None, pattern = None):
  432. """!Returns the output from running g.mlist, as a dictionary where the keys
  433. are mapset names and the values are lists of maps in that mapset.
  434. @param type element type
  435. @param mapset mapset name (default all mapset in search path)
  436. @param pattern pattern string
  437. """
  438. result = {}
  439. mapset_element = None
  440. for line in read_command("g.mlist", flags="m",
  441. type = type, mapset = mapset, pattern = pattern).splitlines():
  442. try:
  443. map, mapset_element = line.split('@')
  444. except ValueError:
  445. print >> sys.stderr, "Invalid element '%s'" % line
  446. continue
  447. if result.has_key(mapset_element):
  448. result[mapset_element].append(map)
  449. else:
  450. result[mapset_element] = [map, ]
  451. return result
  452. def _concat(xs):
  453. result = []
  454. for x in xs:
  455. result.extend(x)
  456. return result
  457. def list_pairs(type):
  458. """!Returns the output from running g.list, as a list of (map, mapset)
  459. pairs. Example:
  460. \code
  461. >>> grass.list_pairs('rast')
  462. [('aspect', 'PERMANENT'), ('erosion1', 'PERMANENT'), ('quads', 'PERMANENT'), ...
  463. \endcode
  464. @param type element type
  465. @return list of tuples (map, mapset)
  466. """
  467. return _concat([[(map, mapset) for map in maps]
  468. for mapset, maps in list_grouped(type).iteritems()])
  469. def list_strings(type):
  470. """!Returns the output from running g.list, as a list of qualified
  471. names. Example:
  472. \code
  473. >>> grass.list_strings('rast')
  474. ['aspect@PERMANENT', 'erosion1@PERMANENT', 'quads@PERMANENT', 'soils@PERMANENT', ...
  475. \endcode
  476. @param type element type
  477. @return list of strings ('map@@mapset')
  478. """
  479. return ["%s@%s" % pair for pair in list_pairs(type)]
  480. # color parsing
  481. named_colors = {
  482. "white": (1.00, 1.00, 1.00),
  483. "black": (0.00, 0.00, 0.00),
  484. "red": (1.00, 0.00, 0.00),
  485. "green": (0.00, 1.00, 0.00),
  486. "blue": (0.00, 0.00, 1.00),
  487. "yellow": (1.00, 1.00, 0.00),
  488. "magenta": (1.00, 0.00, 1.00),
  489. "cyan": (0.00, 1.00, 1.00),
  490. "aqua": (0.00, 0.75, 0.75),
  491. "grey": (0.75, 0.75, 0.75),
  492. "gray": (0.75, 0.75, 0.75),
  493. "orange": (1.00, 0.50, 0.00),
  494. "brown": (0.75, 0.50, 0.25),
  495. "purple": (0.50, 0.00, 1.00),
  496. "violet": (0.50, 0.00, 1.00),
  497. "indigo": (0.00, 0.50, 1.00)}
  498. def parse_color(val, dflt = None):
  499. """!Parses the string "val" as a GRASS colour, which can be either one of
  500. the named colours or an R:G:B tuple e.g. 255:255:255. Returns an
  501. (r,g,b) triple whose components are floating point values between 0
  502. and 1. Example:
  503. \code
  504. >>> grass.parse_color("red")
  505. (1.0, 0.0, 0.0)
  506. >>> grass.parse_color("255:0:0")
  507. (1.0, 0.0, 0.0)
  508. \endcode
  509. @param val color value
  510. @param dflt default color value
  511. @return tuple RGB
  512. """
  513. if val in named_colors:
  514. return named_colors[val]
  515. vals = val.split(':')
  516. if len(vals) == 3:
  517. return tuple(float(v) / 255 for v in vals)
  518. return dflt
  519. # check GRASS_OVERWRITE
  520. def overwrite():
  521. """!Return True if existing files may be overwritten"""
  522. owstr = 'GRASS_OVERWRITE'
  523. return owstr in os.environ and os.environ[owstr] != '0'
  524. # check GRASS_VERBOSE
  525. def verbosity():
  526. """!Return the verbosity level selected by GRASS_VERBOSE"""
  527. vbstr = os.getenv('GRASS_VERBOSE')
  528. if vbstr:
  529. return int(vbstr)
  530. else:
  531. return 0
  532. ## various utilities, not specific to GRASS
  533. # basename inc. extension stripping
  534. def basename(path, ext = None):
  535. """!Remove leading directory components and an optional extension
  536. from the specified path
  537. @param path path
  538. @param ext extension
  539. """
  540. name = os.path.basename(path)
  541. if not ext:
  542. return name
  543. fs = name.rsplit('.', 1)
  544. if len(fs) > 1 and fs[1].lower() == ext:
  545. name = fs[0]
  546. return name
  547. # find a program (replacement for "which")
  548. def find_program(pgm, args = []):
  549. """!Attempt to run a program, with optional arguments. Return False
  550. if the attempt failed due to a missing executable, True otherwise
  551. @param pgm program name
  552. @param args list of arguments
  553. """
  554. nuldev = file(os.devnull, 'w+')
  555. try:
  556. call([pgm] + args, stdin = nuldev, stdout = nuldev, stderr = nuldev)
  557. found = True
  558. except:
  559. found = False
  560. nuldev.close()
  561. return found
  562. # try to remove a file, without complaints
  563. def try_remove(path):
  564. """!Attempt to remove a file; no exception is generated if the
  565. attempt fails.
  566. @param path path
  567. """
  568. try:
  569. os.remove(path)
  570. except:
  571. pass
  572. # try to remove a directory, without complaints
  573. def try_rmdir(path):
  574. """!Attempt to remove a directory; no exception is generated if the
  575. attempt fails.
  576. @param path path
  577. """
  578. try:
  579. os.rmdir(path)
  580. except:
  581. pass
  582. def float_or_dms(s):
  583. """!Convert DMS to float.
  584. @param s DMS value
  585. @return float value
  586. """
  587. return sum(float(x) / 60 ** n for (n, x) in enumerate(s.split(':')))