core.py 28 KB

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