core.py 28 KB

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