core.py 24 KB

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