core.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739
  1. """!@package grass.script.core
  2. @brief GRASS Python scripting module (core functions)
  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-2014 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 shutil
  25. import locale
  26. import codecs
  27. # i18N
  28. import gettext
  29. gettext.install('grasslibs', os.path.join(os.getenv("GISBASE"), 'locale'))
  30. # subprocess wrapper that uses shell on Windows
  31. class Popen(subprocess.Popen):
  32. def __init__(self, args, bufsize=0, executable=None,
  33. stdin=None, stdout=None, stderr=None,
  34. preexec_fn=None, close_fds=False, shell=None,
  35. cwd=None, env=None, universal_newlines=False,
  36. startupinfo=None, creationflags=0):
  37. if shell == None:
  38. shell = (sys.platform == "win32")
  39. if sys.platform == "win32":
  40. # get full path including file extension for scripts
  41. fcmd = get_real_command(args[0])
  42. if fcmd.endswith('.py'):
  43. args[0] = fcmd
  44. args.insert(0, sys.executable)
  45. subprocess.Popen.__init__(self, args, bufsize, executable,
  46. stdin, stdout, stderr,
  47. preexec_fn, close_fds, shell,
  48. cwd, env, universal_newlines,
  49. startupinfo, creationflags)
  50. PIPE = subprocess.PIPE
  51. STDOUT = subprocess.STDOUT
  52. class ScriptError(Exception):
  53. def __init__(self, msg):
  54. self.value = msg
  55. def __str__(self):
  56. return self.value
  57. raise_on_error = False # raise exception instead of calling fatal()
  58. def call(*args, **kwargs):
  59. return Popen(*args, **kwargs).wait()
  60. # GRASS-oriented interface to subprocess module
  61. _popen_args = ["bufsize", "executable", "stdin", "stdout", "stderr",
  62. "preexec_fn", "close_fds", "cwd", "env",
  63. "universal_newlines", "startupinfo", "creationflags"]
  64. def decode(string):
  65. enc = locale.getdefaultlocale()[1]
  66. if enc:
  67. return string.decode(enc)
  68. return string
  69. def encode(string):
  70. enc = locale.getdefaultlocale()[1]
  71. if enc:
  72. return string.encode(enc)
  73. return string
  74. def _make_val(val):
  75. if isinstance(val, types.StringType) or \
  76. isinstance(val, types.UnicodeType):
  77. return val
  78. if isinstance(val, types.ListType):
  79. return ",".join(map(_make_val, val))
  80. if isinstance(val, types.TupleType):
  81. return _make_val(list(val))
  82. return str(val)
  83. def get_commands():
  84. """!Create list of available GRASS commands to use when parsing
  85. string from the command line
  86. @return list of commands (set) and directory of scripts (collected
  87. by extension - MS Windows only)
  88. @code
  89. >>> cmds = list(get_commands()[0])
  90. >>> cmds.sort()
  91. >>> cmds[:5]
  92. ['d.barscale', 'd.colorlist', 'd.colortable', 'd.correlate', 'd.erase']
  93. @endcode
  94. """
  95. gisbase = os.environ['GISBASE']
  96. cmd = list()
  97. scripts = {'.py': list()} if sys.platform == 'win32' else {}
  98. def scan(gisbase, directory):
  99. dir_path = os.path.join(gisbase, directory)
  100. if os.path.exists(dir_path):
  101. for fname in os.listdir(os.path.join(gisbase, directory)):
  102. if scripts: # win32
  103. name, ext = os.path.splitext(fname)
  104. if ext != '.manifest':
  105. cmd.append(name)
  106. if ext in scripts.keys():
  107. scripts[ext].append(name)
  108. else:
  109. cmd.append(fname)
  110. for directory in ('bin', 'scripts'):
  111. scan(gisbase, directory)
  112. # scan gui/scripts/
  113. gui_path = os.path.join(gisbase, 'etc', 'gui', 'scripts')
  114. if os.path.exists(gui_path):
  115. os.environ["PATH"] = os.getenv("PATH") + os.pathsep + gui_path
  116. cmd = cmd + os.listdir(gui_path)
  117. return set(cmd), scripts
  118. # replacement for which function from shutil (not available in all versions)
  119. # from http://hg.python.org/cpython/file/6860263c05b3/Lib/shutil.py#l1068
  120. # added because of Python scripts running Python scripts on MS Windows
  121. # see also ticket #2008 which is unrelated but same function was proposed
  122. def shutil_which(cmd, mode=os.F_OK | os.X_OK, path=None):
  123. """Given a command, mode, and a PATH string, return the path which
  124. conforms to the given mode on the PATH, or None if there is no such
  125. file.
  126. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
  127. of os.environ.get("PATH"), or can be overridden with a custom search
  128. path.
  129. """
  130. # Check that a given file can be accessed with the correct mode.
  131. # Additionally check that `file` is not a directory, as on Windows
  132. # directories pass the os.access check.
  133. def _access_check(fn, mode):
  134. return (os.path.exists(fn) and os.access(fn, mode)
  135. and not os.path.isdir(fn))
  136. # If we're given a path with a directory part, look it up directly rather
  137. # than referring to PATH directories. This includes checking relative to the
  138. # current directory, e.g. ./script
  139. if os.path.dirname(cmd):
  140. if _access_check(cmd, mode):
  141. return cmd
  142. return None
  143. if path is None:
  144. path = os.environ.get("PATH", os.defpath)
  145. if not path:
  146. return None
  147. path = path.split(os.pathsep)
  148. if sys.platform == "win32":
  149. # The current directory takes precedence on Windows.
  150. if not os.curdir in path:
  151. path.insert(0, os.curdir)
  152. # PATHEXT is necessary to check on Windows.
  153. pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
  154. map(lambda x: x.lower(), pathext) # force lowercase
  155. if '.py' not in pathext: # we assume that PATHEXT contains always '.py'
  156. pathext.insert(0, '.py')
  157. # See if the given file matches any of the expected path extensions.
  158. # This will allow us to short circuit when given "python.exe".
  159. # If it does match, only test that one, otherwise we have to try
  160. # others.
  161. if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
  162. files = [cmd]
  163. else:
  164. files = [cmd + ext for ext in pathext]
  165. else:
  166. # On other platforms you don't have things like PATHEXT to tell you
  167. # what file suffixes are executable, so just pass on cmd as-is.
  168. files = [cmd]
  169. seen = set()
  170. for dir in path:
  171. normdir = os.path.normcase(dir)
  172. if not normdir in seen:
  173. seen.add(normdir)
  174. for thefile in files:
  175. name = os.path.join(dir, thefile)
  176. if _access_check(name, mode):
  177. return name
  178. return None
  179. # Added because of scripts calling scripts on MS Windows.
  180. # Module name (here cmd) differs from the file name (does not have extension).
  181. # Additionally, we don't run scripts using system executable mechanism,
  182. # so we need the full path name.
  183. # However, scripts are on the PATH and '.PY' in in PATHEXT, so we can use
  184. # shutil.which to get the full file path. Addons are on PATH too.
  185. # An alternative to which function call would be to check the script path and
  186. # addons path. This is proposed improvement for the future.
  187. # Another alternative is to check some global list of scripts but this list
  188. # needs to be created first. The question is what is less expensive.
  189. # Note that getting the full path is only part of the solution,
  190. # the other part is to use the right Python as an executable and pass the full
  191. # script path as a parameter.
  192. # Nevertheless, it is unclear on which places which extensions are added.
  193. # This function also could skip the check for platform but depends
  194. # how will be used, this is most general but not most effective.
  195. def get_real_command(cmd):
  196. """!Returns the real file commad for a module (cmd)
  197. For Python scripts on MS Windows it returns full path to the script
  198. and adds a '.py' extension.
  199. For other cases it just returns a module (name).
  200. So, you can just use this function for all without further check.
  201. >>> get_real_command('g.region')
  202. 'g.region'
  203. """
  204. if sys.platform == 'win32':
  205. # we in fact expect pure module name (without extension)
  206. # so, lets remove extension
  207. if os.path.splitext(cmd)[1] == '.py':
  208. cmd = cmd[:-3]
  209. full_path = shutil_which(cmd + '.py')
  210. if full_path:
  211. return full_path
  212. return cmd
  213. def make_command(prog, flags="", overwrite=False, quiet=False, verbose=False,
  214. **options):
  215. """!Return a list of strings suitable for use as the args parameter to
  216. Popen() or call(). Example:
  217. @code
  218. >>> make_command("g.message", flags = 'w', message = 'this is a warning')
  219. ['g.message', '-w', 'message=this is a warning']
  220. @endcode
  221. @param prog GRASS module
  222. @param flags flags to be used (given as a string)
  223. @param overwrite True to enable overwriting the output (<tt>--o</tt>)
  224. @param quiet True to run quietly (<tt>--q</tt>)
  225. @param verbose True to run verbosely (<tt>--v</tt>)
  226. @param options module's parameters
  227. @return list of arguments
  228. """
  229. args = [prog]
  230. if overwrite:
  231. args.append("--o")
  232. if quiet:
  233. args.append("--q")
  234. if verbose:
  235. args.append("--v")
  236. if flags:
  237. if '-' in flags:
  238. raise ScriptError("'-' is not a valid flag")
  239. args.append("-%s" % flags)
  240. for opt, val in options.iteritems():
  241. if val != None:
  242. if opt[0] == '_':
  243. opt = opt[1:]
  244. args.append("%s=%s" % (opt, _make_val(val)))
  245. return args
  246. def start_command(prog, flags="", overwrite=False, quiet=False,
  247. verbose=False, **kwargs):
  248. """!Returns a Popen object with the command created by make_command.
  249. Accepts any of the arguments which Popen() accepts apart from "args"
  250. and "shell".
  251. @code
  252. >>> p = start_command("g.gisenv", stdout=subprocess.PIPE)
  253. >>> print p # doctest: +ELLIPSIS
  254. <...Popen object at 0x...>
  255. >>> print p.communicate()[0] # doctest: +SKIP
  256. GISDBASE='/opt/grass-data';
  257. LOCATION_NAME='spearfish60';
  258. MAPSET='glynn';
  259. GRASS_DB_ENCODING='ascii';
  260. GUI='text';
  261. MONITOR='x0';
  262. @endcode
  263. @param prog GRASS module
  264. @param flags flags to be used (given as a string)
  265. @param overwrite True to enable overwriting the output (<tt>--o</tt>)
  266. @param quiet True to run quietly (<tt>--q</tt>)
  267. @param verbose True to run verbosely (<tt>--v</tt>)
  268. @param kwargs module's parameters
  269. @return Popen object
  270. """
  271. options = {}
  272. popts = {}
  273. for opt, val in kwargs.iteritems():
  274. if opt in _popen_args:
  275. popts[opt] = val
  276. else:
  277. if isinstance(val, unicode):
  278. val = encode(val)
  279. options[opt] = val
  280. args = make_command(prog, flags, overwrite, quiet, verbose, **options)
  281. if debug_level() > 0:
  282. sys.stderr.write("D1/%d: %s.start_command(): %s\n" % (debug_level(),
  283. __name__,
  284. ' '.join(args)))
  285. sys.stderr.flush()
  286. return Popen(args, **popts)
  287. def run_command(*args, **kwargs):
  288. """!Passes all arguments to start_command(), then waits for the process to
  289. complete, returning its exit code. Similar to subprocess.call(), but
  290. with the make_command() interface.
  291. @param args list of unnamed arguments (see start_command() for details)
  292. @param kwargs list of named arguments (see start_command() for details)
  293. @return exit code (0 for success)
  294. """
  295. ps = start_command(*args, **kwargs)
  296. return ps.wait()
  297. def pipe_command(*args, **kwargs):
  298. """!Passes all arguments to start_command(), but also adds
  299. "stdout = PIPE". Returns the Popen object.
  300. @code
  301. >>> p = pipe_command("g.gisenv")
  302. >>> print p # doctest: +ELLIPSIS
  303. <....Popen object at 0x...>
  304. >>> print p.communicate()[0] # doctest: +SKIP
  305. GISDBASE='/opt/grass-data';
  306. LOCATION_NAME='spearfish60';
  307. MAPSET='glynn';
  308. GRASS_DB_ENCODING='ascii';
  309. GUI='text';
  310. MONITOR='x0';
  311. @endcode
  312. @param args list of unnamed arguments (see start_command() for details)
  313. @param kwargs list of named arguments (see start_command() for details)
  314. @return Popen object
  315. """
  316. kwargs['stdout'] = PIPE
  317. return start_command(*args, **kwargs)
  318. def feed_command(*args, **kwargs):
  319. """!Passes all arguments to start_command(), but also adds
  320. "stdin = PIPE". Returns the Popen object.
  321. @param args list of unnamed arguments (see start_command() for details)
  322. @param kwargs list of named arguments (see start_command() for details)
  323. @return Popen object
  324. """
  325. kwargs['stdin'] = PIPE
  326. return start_command(*args, **kwargs)
  327. def read_command(*args, **kwargs):
  328. """!Passes all arguments to pipe_command, then waits for the process to
  329. complete, returning its stdout (i.e. similar to shell `backticks`).
  330. @param args list of unnamed arguments (see start_command() for details)
  331. @param kwargs list of named arguments (see start_command() for details)
  332. @return stdout
  333. """
  334. ps = pipe_command(*args, **kwargs)
  335. return ps.communicate()[0]
  336. def parse_command(*args, **kwargs):
  337. """!Passes all arguments to read_command, then parses the output
  338. by parse_key_val().
  339. Parsing function can be optionally given by <em>parse</em> parameter
  340. including its arguments, e.g.
  341. @code
  342. parse_command(..., parse = (grass.parse_key_val, { 'sep' : ':' }))
  343. @endcode
  344. or you can simply define <em>delimiter</em>
  345. @code
  346. parse_command(..., delimiter = ':')
  347. @endcode
  348. @param args list of unnamed arguments (see start_command() for details)
  349. @param kwargs list of named arguments (see start_command() for details)
  350. @return parsed module output
  351. """
  352. parse = None
  353. parse_args = {}
  354. if 'parse' in kwargs:
  355. if type(kwargs['parse']) is types.TupleType:
  356. parse = kwargs['parse'][0]
  357. parse_args = kwargs['parse'][1]
  358. del kwargs['parse']
  359. if 'delimiter' in kwargs:
  360. parse_args = {'sep': kwargs['delimiter']}
  361. del kwargs['delimiter']
  362. if not parse:
  363. parse = parse_key_val # use default fn
  364. res = read_command(*args, **kwargs)
  365. return parse(res, **parse_args)
  366. def write_command(*args, **kwargs):
  367. """!Passes all arguments to feed_command, with the string specified
  368. by the 'stdin' argument fed to the process' stdin.
  369. @param args list of unnamed arguments (see start_command() for details)
  370. @param kwargs list of named arguments (see start_command() for details)
  371. @return return code
  372. """
  373. stdin = kwargs['stdin']
  374. p = feed_command(*args, **kwargs)
  375. p.stdin.write(stdin)
  376. p.stdin.close()
  377. return p.wait()
  378. def exec_command(prog, flags="", overwrite=False, quiet=False, verbose=False,
  379. env=None, **kwargs):
  380. """!Interface to os.execvpe(), but with the make_command() interface.
  381. @param prog GRASS module
  382. @param flags flags to be used (given as a string)
  383. @param overwrite True to enable overwriting the output (<tt>--o</tt>)
  384. @param quiet True to run quietly (<tt>--q</tt>)
  385. @param verbose True to run verbosely (<tt>--v</tt>)
  386. @param env directory with environmental variables
  387. @param kwargs module's parameters
  388. """
  389. args = make_command(prog, flags, overwrite, quiet, verbose, **kwargs)
  390. if env == None:
  391. env = os.environ
  392. os.execvpe(prog, args, env)
  393. # interface to g.message
  394. def message(msg, flag=None):
  395. """!Display a message using `g.message`
  396. @param msg message to be displayed
  397. @param flag flags (given as string)
  398. """
  399. run_command("g.message", flags=flag, message=msg)
  400. def debug(msg, debug=1):
  401. """!Display a debugging message using `g.message -d`
  402. @param msg debugging message to be displayed
  403. @param debug debug level (0-5)
  404. """
  405. if debug_level() >= debug:
  406. if sys.platform == "win32":
  407. msg = msg.replace('&', '^&')
  408. run_command("g.message", flags='d', message=msg, debug=debug)
  409. def verbose(msg):
  410. """!Display a verbose message using `g.message -v`
  411. @param msg verbose message to be displayed
  412. """
  413. message(msg, flag='v')
  414. def info(msg):
  415. """!Display an informational message using `g.message -i`
  416. @param msg informational message to be displayed
  417. """
  418. message(msg, flag='i')
  419. def percent(i, n, s):
  420. """!Display a progress info message using `g.message -p`
  421. @code
  422. message(_("Percent complete..."))
  423. n = 100
  424. for i in range(n):
  425. percent(i, n, 1)
  426. percent(1, 1, 1)
  427. @endcode
  428. @param i current item
  429. @param n total number of items
  430. @param s increment size
  431. """
  432. message("%d %d %d" % (i, n, s), flag='p')
  433. def warning(msg):
  434. """!Display a warning message using `g.message -w`
  435. @param msg warning message to be displayed
  436. """
  437. message(msg, flag='w')
  438. def error(msg):
  439. """!Display an error message using `g.message -e`
  440. @param msg error message to be displayed
  441. """
  442. message(msg, flag='e')
  443. def fatal(msg):
  444. """!Display an error message using `g.message -e`, then abort
  445. Raise exception when raise_on_error is 'True'.
  446. @param msg error message to be displayed
  447. """
  448. global raise_on_error
  449. if raise_on_error:
  450. raise ScriptError(msg)
  451. error(msg)
  452. sys.exit(1)
  453. def set_raise_on_error(raise_exp=True):
  454. """!Define behaviour on fatal error (fatal() called)
  455. @param raise_exp True to raise ScriptError instead of calling
  456. sys.exit(1) in fatal()
  457. @return current status
  458. """
  459. global raise_on_error
  460. tmp_raise = raise_on_error
  461. raise_on_error = raise_exp
  462. return tmp_raise
  463. def get_raise_on_error():
  464. """!Return True if a ScriptError exception is raised instead of calling
  465. sys.exit(1) in case a fatal error was invoked with fatal()
  466. """
  467. global raise_on_error
  468. return raise_on_error
  469. # interface to g.parser
  470. def _parse_opts(lines):
  471. options = {}
  472. flags = {}
  473. for line in lines:
  474. if not line:
  475. break
  476. try:
  477. [var, val] = line.split('=', 1)
  478. except:
  479. raise SyntaxError("invalid output from g.parser: %s" % line)
  480. if var.startswith('flag_'):
  481. flags[var[5:]] = bool(int(val))
  482. elif var.startswith('opt_'):
  483. options[var[4:]] = val
  484. elif var in ['GRASS_OVERWRITE', 'GRASS_VERBOSE']:
  485. os.environ[var] = val
  486. else:
  487. raise SyntaxError("invalid output from g.parser: %s" % line)
  488. return (options, flags)
  489. def parser():
  490. """!Interface to g.parser, intended to be run from the top-level, e.g.:
  491. @code
  492. if __name__ == "__main__":
  493. options, flags = grass.parser()
  494. main()
  495. @endcode
  496. Thereafter, the global variables "options" and "flags" will be
  497. dictionaries containing option/flag values, keyed by lower-case
  498. option/flag names. The values in "options" are strings, those in
  499. "flags" are Python booleans.
  500. """
  501. if not os.getenv("GISBASE"):
  502. print >> sys.stderr, "You must be in GRASS GIS to run this program."
  503. sys.exit(1)
  504. cmdline = [basename(sys.argv[0])]
  505. cmdline += ['"' + arg + '"' for arg in sys.argv[1:]]
  506. os.environ['CMDLINE'] = ' '.join(cmdline)
  507. argv = sys.argv[:]
  508. name = argv[0]
  509. if not os.path.isabs(name):
  510. if os.sep in name or (os.altsep and os.altsep in name):
  511. argv[0] = os.path.abspath(name)
  512. else:
  513. argv[0] = os.path.join(sys.path[0], name)
  514. p = Popen(['g.parser', '-n'] + argv, stdout=PIPE)
  515. s = p.communicate()[0]
  516. lines = s.split('\0')
  517. if not lines or lines[0] != "@ARGS_PARSED@":
  518. sys.stdout.write(s)
  519. sys.exit(p.returncode)
  520. return _parse_opts(lines[1:])
  521. def separator(sep):
  522. """!Returns separator from G_OPT_F_SEP appropriately converted
  523. to character.
  524. @param separator character or separator keyword
  525. @return separator character
  526. """
  527. if sep == "pipe":
  528. return "|"
  529. elif sep == "comma":
  530. return ","
  531. elif sep == "space":
  532. return " "
  533. elif sep == "tab" or sep == "\\t":
  534. return "\t"
  535. elif sep == "newline" or sep == "\\n":
  536. return "\n"
  537. return sep
  538. # interface to g.tempfile
  539. def tempfile(create=True):
  540. """!Returns the name of a temporary file, created with
  541. g.tempfile.
  542. @param create True to create a file
  543. @return path to a tmp file
  544. """
  545. flags = ''
  546. if not create:
  547. flags += 'd'
  548. return read_command("g.tempfile", flags=flags, pid=os.getpid()).strip()
  549. def tempdir():
  550. """!Returns the name of a temporary dir, created with g.tempfile."""
  551. tmp = tempfile(create=False)
  552. os.mkdir(tmp)
  553. return tmp
  554. class KeyValue(dict):
  555. """A general-purpose key-value store.
  556. KeyValue is a subclass of dict, but also allows entries to be read and
  557. written using attribute syntax. Example:
  558. \code
  559. >>> reg = KeyValue()
  560. >>> reg['north'] = 489
  561. >>> reg.north
  562. 489
  563. >>> reg.south = 205
  564. >>> reg['south']
  565. 205
  566. \endcode
  567. """
  568. def __getattr__(self, key):
  569. return self[key]
  570. def __setattr__(self, key, value):
  571. self[key] = value
  572. # key-value parsers
  573. def parse_key_val(s, sep='=', dflt=None, val_type=None, vsep=None):
  574. """!Parse a string into a dictionary, where entries are separated
  575. by newlines and the key and value are separated by `sep' (default: `=')
  576. @param s string to be parsed
  577. @param sep key/value separator
  578. @param dflt default value to be used
  579. @param val_type value type (None for no cast)
  580. @param vsep vertical separator (default os.linesep)
  581. @return parsed input (dictionary of keys/values)
  582. """
  583. result = KeyValue()
  584. if not s:
  585. return result
  586. if vsep:
  587. lines = s.split(vsep)
  588. try:
  589. lines.remove('\n')
  590. except ValueError:
  591. pass
  592. else:
  593. lines = s.splitlines()
  594. for line in lines:
  595. kv = line.split(sep, 1)
  596. k = kv[0].strip()
  597. if len(kv) > 1:
  598. v = kv[1].strip()
  599. else:
  600. v = dflt
  601. if val_type:
  602. result[k] = val_type(v)
  603. else:
  604. result[k] = v
  605. return result
  606. def _compare_projection(dic):
  607. """
  608. !Check if projection has some possibility of duplicate names like
  609. Universal Transverse Mercator and Universe Transverse Mercator and
  610. unify them
  611. @param dic The dictionary containing information about projection
  612. @return The dictionary with the new values if needed
  613. """
  614. # the lookup variable is a list of list, each list contains all the
  615. # possible name for a projection system
  616. lookup = [['Universal Transverse Mercator', 'Universe Transverse Mercator']]
  617. for lo in lookup:
  618. for n in range(len(dic['name'])):
  619. if dic['name'][n] in lo:
  620. dic['name'][n] = lo[0]
  621. return dic
  622. def _compare_units(dic):
  623. """
  624. !Check if units has some possibility of duplicate names like
  625. meter and metre and unify them
  626. @param dic The dictionary containing information about units
  627. @return The dictionary with the new values if needed
  628. """
  629. # the lookup variable is a list of list, each list contains all the
  630. # possible name for a units
  631. lookup = [['meter', 'metre'], ['meters', 'metres'], ['kilometer',
  632. 'kilometre'], ['kilometers', 'kilometres']]
  633. for l in lookup:
  634. for n in range(len(dic['unit'])):
  635. if dic['unit'][n] in l:
  636. dic['unit'][n] = l[0]
  637. for n in range(len(dic['units'])):
  638. if dic['units'][n] in l:
  639. dic['units'][n] = l[0]
  640. return dic
  641. def _text_to_key_value_dict(filename, sep=":", val_sep=",", checkproj=False,
  642. checkunits=False):
  643. """
  644. !Convert a key-value text file, where entries are separated
  645. by newlines and the key and value are separated by `sep',
  646. into a key-value dictionary and discover/use the correct
  647. data types (float, int or string) for values.
  648. @param filename The name or name and path of the text file to convert
  649. @param sep The character that separates the keys and values, default is ":"
  650. @param val_sep The character that separates the values of a single key, default is ","
  651. @param checkproj True if it has to check some information about projection system
  652. @param checkproj True if it has to check some information about units
  653. @return The dictionary
  654. A text file with this content:
  655. \code
  656. a: Hello
  657. b: 1.0
  658. c: 1,2,3,4,5
  659. d : hello,8,0.1
  660. \endcode
  661. Will be represented as this dictionary:
  662. \code
  663. {'a': ['Hello'], 'c': [1, 2, 3, 4, 5], 'b': [1.0], 'd': ['hello', 8, 0.1]}
  664. \endcode
  665. """
  666. text = open(filename, "r").readlines()
  667. kvdict = KeyValue()
  668. for line in text:
  669. if line.find(sep) >= 0:
  670. key, value = line.split(sep)
  671. key = key.strip()
  672. value = value.strip()
  673. else:
  674. # Jump over empty values
  675. continue
  676. values = value.split(val_sep)
  677. value_list = []
  678. for value in values:
  679. not_float = False
  680. not_int = False
  681. # Convert values into correct types
  682. # We first try integer then float
  683. try:
  684. value_converted = int(value)
  685. except:
  686. not_int = True
  687. if not_int:
  688. try:
  689. value_converted = float(value)
  690. except:
  691. not_float = True
  692. if not_int and not_float:
  693. value_converted = value.strip()
  694. value_list.append(value_converted)
  695. kvdict[key] = value_list
  696. if checkproj:
  697. kvdict = _compare_projection(kvdict)
  698. if checkunits:
  699. kvdict = _compare_units(kvdict)
  700. return kvdict
  701. def compare_key_value_text_files(filename_a, filename_b, sep=":",
  702. val_sep=",", precision=0.000001,
  703. proj=False, units=False):
  704. """
  705. !Compare two key-value text files
  706. This method will print a warning in case keys that are present in the first
  707. file are not present in the second one.
  708. The comparison method tries to convert the values into their native format
  709. (float, int or string) to allow correct comparison.
  710. An example key-value text file may have this content:
  711. \code
  712. a: Hello
  713. b: 1.0
  714. c: 1,2,3,4,5
  715. d : hello,8,0.1
  716. \endcode
  717. @param filename_a name of the first key-value text file
  718. @param filenmae_b name of the second key-value text file
  719. @param sep character that separates the keys and values, default is ":"
  720. @param val_sep character that separates the values of a single key, default is ","
  721. @param precision precision with which the floating point values are compared
  722. @param proj True if it has to check some information about projection system
  723. @param units True if it has to check some information about units
  724. @return True if full or almost identical, False if different
  725. """
  726. dict_a = _text_to_key_value_dict(filename_a, sep, checkproj=proj,
  727. checkunits=units)
  728. dict_b = _text_to_key_value_dict(filename_b, sep, checkproj=proj,
  729. checkunits=units)
  730. if sorted(dict_a.keys()) != sorted(dict_b.keys()):
  731. return False
  732. # We compare matching keys
  733. for key in dict_a.keys():
  734. # Floating point values must be handled separately
  735. if isinstance(dict_a[key], float) and isinstance(dict_b[key], float):
  736. if abs(dict_a[key] - dict_b[key]) > precision:
  737. return False
  738. elif isinstance(dict_a[key], float) or isinstance(dict_b[key], float):
  739. warning(_("Mixing value types. Will try to compare after "
  740. "integer conversion"))
  741. return int(dict_a[key]) == int(dict_b[key])
  742. elif key == "+towgs84":
  743. # We compare the sum of the entries
  744. if abs(sum(dict_a[key]) - sum(dict_b[key])) > precision:
  745. return False
  746. else:
  747. if dict_a[key] != dict_b[key]:
  748. return False
  749. return True
  750. def diff_files(filename_a, filename_b):
  751. """!Diffs two text files and returns difference.
  752. @param filename_a first file path
  753. @param filename_b second file path
  754. @return list of strings
  755. """
  756. import difflib
  757. differ = difflib.Differ()
  758. fh_a = open(filename_a, 'r')
  759. fh_b = open(filename_b, 'r')
  760. result = list(differ.compare(fh_a.readlines(),
  761. fh_b.readlines()))
  762. return result
  763. # interface to g.gisenv
  764. def gisenv():
  765. """!Returns the output from running g.gisenv (with no arguments), as a
  766. dictionary. Example:
  767. @code
  768. >>> env = gisenv()
  769. >>> print env['GISDBASE'] # doctest: +SKIP
  770. /opt/grass-data
  771. @endcode
  772. @return list of GRASS variables
  773. """
  774. s = read_command("g.gisenv", flags='n')
  775. return parse_key_val(s)
  776. # interface to g.region
  777. def locn_is_latlong():
  778. """!Tests if location is lat/long. Value is obtained
  779. by checking the "g.region -pu" projection code.
  780. @return True for a lat/long region, False otherwise
  781. """
  782. s = read_command("g.region", flags='pu')
  783. kv = parse_key_val(s, ':')
  784. if kv['projection'].split(' ')[0] == '3':
  785. return True
  786. else:
  787. return False
  788. def region(region3d=False, complete=False):
  789. """!Returns the output from running "g.region -gu", as a
  790. dictionary. Example:
  791. @param region3d True to get 3D region
  792. @code
  793. >>> curent_region = region()
  794. >>> # obtain n, s, e and w values
  795. >>> [curent_region[key] for key in "nsew"] # doctest: +ELLIPSIS
  796. [..., ..., ..., ...]
  797. >>> # obtain ns and ew resulutions
  798. >>> (curent_region['nsres'], curent_region['ewres']) # doctest: +ELLIPSIS
  799. (..., ...)
  800. @endcode
  801. @return dictionary of region values
  802. """
  803. flgs = 'gu'
  804. if region3d:
  805. flgs += '3'
  806. if complete:
  807. flgs += 'cep'
  808. s = read_command("g.region", flags=flgs)
  809. reg = parse_key_val(s, val_type=float)
  810. for k in ['rows', 'cols', 'cells',
  811. 'rows3', 'cols3', 'cells3', 'depths']:
  812. if k not in reg:
  813. continue
  814. reg[k] = int(reg[k])
  815. return reg
  816. def region_env(region3d=False, **kwargs):
  817. """!Returns region settings as a string which can used as
  818. GRASS_REGION environmental variable.
  819. If no 'kwargs' are given then the current region is used. Note
  820. that this function doesn't modify the current region!
  821. See also use_temp_region() for alternative method how to define
  822. temporary region used for raster-based computation.
  823. \param region3d True to get 3D region
  824. \param kwargs g.region's parameters like 'rast', 'vect' or 'region'
  825. \code
  826. os.environ['GRASS_REGION'] = grass.region_env(region='detail')
  827. grass.mapcalc('map=1', overwrite=True)
  828. os.environ.pop('GRASS_REGION')
  829. \endcode
  830. @return string with region values
  831. @return empty string on error
  832. """
  833. # read proj/zone from WIND file
  834. env = gisenv()
  835. windfile = os.path.join(env['GISDBASE'], env['LOCATION_NAME'],
  836. env['MAPSET'], "WIND")
  837. fd = open(windfile, "r")
  838. grass_region = ''
  839. for line in fd.readlines():
  840. key, value = map(lambda x: x.strip(), line.split(":", 1))
  841. if kwargs and key not in ('proj', 'zone'):
  842. continue
  843. if not kwargs and not region3d and \
  844. key in ('top', 'bottom', 'cols3', 'rows3',
  845. 'depths', 'e-w resol3', 'n-s resol3', 't-b resol'):
  846. continue
  847. grass_region += '%s: %s;' % (key, value)
  848. if not kwargs: # return current region
  849. return grass_region
  850. # read other values from `g.region -gu`
  851. flgs = 'ug'
  852. if region3d:
  853. flgs += '3'
  854. s = read_command('g.region', flags=flgs, **kwargs)
  855. if not s:
  856. return ''
  857. reg = parse_key_val(s)
  858. kwdata = [('north', 'n'),
  859. ('south', 's'),
  860. ('east', 'e'),
  861. ('west', 'w'),
  862. ('cols', 'cols'),
  863. ('rows', 'rows'),
  864. ('e-w resol', 'ewres'),
  865. ('n-s resol', 'nsres')]
  866. if region3d:
  867. kwdata += [('top', 't'),
  868. ('bottom', 'b'),
  869. ('cols3', 'cols3'),
  870. ('rows3', 'rows3'),
  871. ('depths', 'depths'),
  872. ('e-w resol3', 'ewres3'),
  873. ('n-s resol3', 'nsres3'),
  874. ('t-b resol', 'tbres')]
  875. for wkey, rkey in kwdata:
  876. grass_region += '%s: %s;' % (wkey, reg[rkey])
  877. return grass_region
  878. def use_temp_region():
  879. """!Copies the current region to a temporary region with "g.region save=",
  880. then sets WIND_OVERRIDE to refer to that region. Installs an atexit
  881. handler to delete the temporary region upon termination.
  882. """
  883. name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
  884. run_command("g.region", save=name, overwrite=True)
  885. os.environ['WIND_OVERRIDE'] = name
  886. atexit.register(del_temp_region)
  887. def del_temp_region():
  888. """!Unsets WIND_OVERRIDE and removes any region named by it."""
  889. try:
  890. name = os.environ.pop('WIND_OVERRIDE')
  891. run_command("g.remove", quiet=True, region=name)
  892. except:
  893. pass
  894. # interface to g.findfile
  895. def find_file(name, element='cell', mapset=None):
  896. """!Returns the output from running g.findfile as a
  897. dictionary. Example:
  898. @code
  899. >>> result = find_file('elevation', element='cell')
  900. >>> print result['fullname']
  901. elevation@PERMANENT
  902. >>> print result['file'] # doctest: +ELLIPSIS
  903. /.../PERMANENT/cell/elevation
  904. @endcode
  905. @param name file name
  906. @param element element type (default 'cell')
  907. @param mapset mapset name (default all mapsets in search path)
  908. @return parsed output of g.findfile
  909. """
  910. if element == 'raster' or element == 'rast':
  911. verbose(_('Element type should be "cell" and not "%s"') % element)
  912. element = 'cell'
  913. s = read_command("g.findfile", flags='n', element=element, file=name,
  914. mapset=mapset)
  915. return parse_key_val(s)
  916. # interface to g.list
  917. def list_grouped(type, check_search_path=True):
  918. """!List elements grouped by mapsets.
  919. Returns the output from running g.list, as a dictionary where the
  920. keys are mapset names and the values are lists of maps in that
  921. mapset. Example:
  922. @code
  923. >>> list_grouped('rast')['PERMANENT'] # doctest: +ELLIPSIS
  924. [..., 'lakes', ..., 'slope', ...
  925. @endcode
  926. @param type element type (rast, vect, rast3d, region, ...)
  927. @param check_search_path True to add mapsets for the search path with no
  928. found elements
  929. @return directory of mapsets/elements
  930. """
  931. if type == 'raster' or type == 'cell':
  932. verbose(_('Element type should be "rast" and not "%s"') % type)
  933. type = 'rast'
  934. dashes_re = re.compile("^----+$")
  935. mapset_re = re.compile("<(.*)>")
  936. result = {}
  937. if check_search_path:
  938. for mapset in mapsets(search_path=True):
  939. result[mapset] = []
  940. mapset = None
  941. for line in read_command("g.list", type=type).splitlines():
  942. if line == "":
  943. continue
  944. if dashes_re.match(line):
  945. continue
  946. m = mapset_re.search(line)
  947. if m:
  948. mapset = m.group(1)
  949. if mapset not in result.keys():
  950. result[mapset] = []
  951. continue
  952. if mapset:
  953. result[mapset].extend(line.split())
  954. return result
  955. def _concat(xs):
  956. result = []
  957. for x in xs:
  958. result.extend(x)
  959. return result
  960. def list_pairs(type):
  961. """!List of elements as tuples.
  962. Returns the output from running g.list, as a list of (map, mapset)
  963. pairs. Example:
  964. @code
  965. >>> list_pairs('rast') # doctest: +ELLIPSIS
  966. [..., ('lakes', 'PERMANENT'), ..., ('slope', 'PERMANENT'), ...
  967. @endcode
  968. @param type element type (rast, vect, rast3d, region, ...)
  969. @return list of tuples (map, mapset)
  970. """
  971. return _concat([[(map, mapset) for map in maps]
  972. for mapset, maps in list_grouped(type).iteritems()])
  973. def list_strings(type):
  974. """!List of elements as strings.
  975. Returns the output from running g.list, as a list of qualified
  976. names. Example:
  977. @code
  978. >>> list_strings('rast') # doctest: +ELLIPSIS
  979. [..., 'lakes@PERMANENT', ..., 'slope@PERMANENT', ...
  980. @endcode
  981. @param type element type
  982. @return list of strings ('map@@mapset')
  983. """
  984. return ["%s@%s" % pair for pair in list_pairs(type)]
  985. # interface to g.mlist
  986. def mlist_strings(type, pattern=None, mapset=None, flag=''):
  987. """!List of elements as strings.
  988. Returns the output from running g.mlist, as a list of qualified
  989. names.
  990. @param type element type (rast, vect, rast3d, region, ...)
  991. @param pattern pattern string
  992. @param mapset mapset name (if not given use search path)
  993. @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or ''
  994. (glob pattern)
  995. @return list of elements
  996. """
  997. if type == 'raster' or type == 'cell':
  998. verbose(_('Element type should be "rast" and not "%s"') % type)
  999. type = 'rast'
  1000. result = list()
  1001. for line in read_command("g.mlist",
  1002. quiet=True,
  1003. flags='m' + flag,
  1004. type=type,
  1005. pattern=pattern,
  1006. mapset=mapset).splitlines():
  1007. result.append(line.strip())
  1008. return result
  1009. def mlist_pairs(type, pattern=None, mapset=None, flag=''):
  1010. """!List of elements as pairs
  1011. Returns the output from running g.mlist, as a list of
  1012. (name, mapset) pairs
  1013. @param type element type (rast, vect, rast3d, region, ...)
  1014. @param pattern pattern string
  1015. @param mapset mapset name (if not given use search path)
  1016. @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or ''
  1017. (glob pattern)
  1018. @return list of elements
  1019. """
  1020. return [tuple(map.split('@', 1)) for map in mlist_strings(type, pattern,
  1021. mapset, flag)]
  1022. def mlist_grouped(type, pattern=None, check_search_path=True, flag=''):
  1023. """!List of elements grouped by mapsets.
  1024. Returns the output from running g.mlist, as a dictionary where the
  1025. keys are mapset names and the values are lists of maps in that
  1026. mapset. Example:
  1027. @code
  1028. >>> mlist_grouped('vect', pattern='*roads*')['PERMANENT']
  1029. ['railroads', 'roadsmajor']
  1030. @endcode
  1031. @param type element type (rast, vect, rast3d, region, ...)
  1032. @param pattern pattern string
  1033. @param check_search_path True to add mapsets for the search path with no
  1034. found elements
  1035. @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or ''
  1036. (glob pattern)
  1037. @return directory of mapsets/elements
  1038. """
  1039. if type == 'raster' or type == 'cell':
  1040. verbose(_('Element type should be "rast" and not "%s"') % type)
  1041. type = 'rast'
  1042. result = {}
  1043. if check_search_path:
  1044. for mapset in mapsets(search_path=True):
  1045. result[mapset] = []
  1046. mapset = None
  1047. for line in read_command("g.mlist", quiet=True, flags="m" + flag,
  1048. type=type, pattern=pattern).splitlines():
  1049. try:
  1050. name, mapset = line.split('@')
  1051. except ValueError:
  1052. warning(_("Invalid element '%s'") % line)
  1053. continue
  1054. if mapset in result:
  1055. result[mapset].append(name)
  1056. else:
  1057. result[mapset] = [name, ]
  1058. return result
  1059. # color parsing
  1060. named_colors = {
  1061. "white": (1.00, 1.00, 1.00),
  1062. "black": (0.00, 0.00, 0.00),
  1063. "red": (1.00, 0.00, 0.00),
  1064. "green": (0.00, 1.00, 0.00),
  1065. "blue": (0.00, 0.00, 1.00),
  1066. "yellow": (1.00, 1.00, 0.00),
  1067. "magenta": (1.00, 0.00, 1.00),
  1068. "cyan": (0.00, 1.00, 1.00),
  1069. "aqua": (0.00, 0.75, 0.75),
  1070. "grey": (0.75, 0.75, 0.75),
  1071. "gray": (0.75, 0.75, 0.75),
  1072. "orange": (1.00, 0.50, 0.00),
  1073. "brown": (0.75, 0.50, 0.25),
  1074. "purple": (0.50, 0.00, 1.00),
  1075. "violet": (0.50, 0.00, 1.00),
  1076. "indigo": (0.00, 0.50, 1.00)}
  1077. def parse_color(val, dflt=None):
  1078. """!Parses the string "val" as a GRASS colour, which can be either one of
  1079. the named colours or an R:G:B tuple e.g. 255:255:255. Returns an
  1080. (r,g,b) triple whose components are floating point values between 0
  1081. and 1. Example:
  1082. @code
  1083. >>> parse_color("red")
  1084. (1.0, 0.0, 0.0)
  1085. >>> parse_color("255:0:0")
  1086. (1.0, 0.0, 0.0)
  1087. @endcode
  1088. @param val color value
  1089. @param dflt default color value
  1090. @return tuple RGB
  1091. """
  1092. if val in named_colors:
  1093. return named_colors[val]
  1094. vals = val.split(':')
  1095. if len(vals) == 3:
  1096. return tuple(float(v) / 255 for v in vals)
  1097. return dflt
  1098. # check GRASS_OVERWRITE
  1099. def overwrite():
  1100. """!Return True if existing files may be overwritten"""
  1101. owstr = 'GRASS_OVERWRITE'
  1102. return owstr in os.environ and os.environ[owstr] != '0'
  1103. # check GRASS_VERBOSE
  1104. def verbosity():
  1105. """!Return the verbosity level selected by GRASS_VERBOSE"""
  1106. vbstr = os.getenv('GRASS_VERBOSE')
  1107. if vbstr:
  1108. return int(vbstr)
  1109. else:
  1110. return 2
  1111. ## various utilities, not specific to GRASS
  1112. # basename inc. extension stripping
  1113. def basename(path, ext=None):
  1114. """!Remove leading directory components and an optional extension
  1115. from the specified path
  1116. @param path path
  1117. @param ext extension
  1118. """
  1119. name = os.path.basename(path)
  1120. if not ext:
  1121. return name
  1122. fs = name.rsplit('.', 1)
  1123. if len(fs) > 1 and fs[1].lower() == ext:
  1124. name = fs[0]
  1125. return name
  1126. def find_program(pgm, *args):
  1127. """!Attempt to run a program, with optional arguments.
  1128. You must call the program in a way that will return a successful
  1129. exit code. For GRASS modules this means you need to pass it some
  1130. valid CLI option, like "--help". For other programs a common
  1131. valid do-little option is "--version".
  1132. Example:
  1133. @code
  1134. >>> grass.find_program('r.sun', 'help')
  1135. True
  1136. >>> grass.find_program('gdalwarp', '--version')
  1137. True
  1138. @endcode
  1139. @param pgm program name
  1140. @param args list of arguments
  1141. @return False if the attempt failed due to a missing executable
  1142. or non-zero return code
  1143. @return True otherwise
  1144. """
  1145. nuldev = file(os.devnull, 'w+')
  1146. try:
  1147. call([pgm] + list(args), stdin = nuldev, stdout = nuldev, stderr = nuldev)
  1148. found = True
  1149. except:
  1150. found = False
  1151. nuldev.close()
  1152. return found
  1153. # try to remove a file, without complaints
  1154. def try_remove(path):
  1155. """!Attempt to remove a file; no exception is generated if the
  1156. attempt fails.
  1157. @param path path to file to remove
  1158. """
  1159. try:
  1160. os.remove(path)
  1161. except:
  1162. pass
  1163. # try to remove a directory, without complaints
  1164. def try_rmdir(path):
  1165. """!Attempt to remove a directory; no exception is generated if the
  1166. attempt fails.
  1167. @param path path to directory to remove
  1168. """
  1169. try:
  1170. os.rmdir(path)
  1171. except:
  1172. shutil.rmtree(path, ignore_errors=True)
  1173. def float_or_dms(s):
  1174. """!Convert DMS to float.
  1175. @param s DMS value
  1176. @return float value
  1177. """
  1178. return sum(float(x) / 60 ** n for (n, x) in enumerate(s.split(':')))
  1179. # interface to g.mapsets
  1180. def mapsets(search_path=False):
  1181. """!List available mapsets
  1182. @param search_path True to list mapsets only in search path
  1183. @return list of mapsets
  1184. """
  1185. if search_path:
  1186. flags = 'p'
  1187. else:
  1188. flags = 'l'
  1189. mapsets = read_command('g.mapsets',
  1190. flags=flags,
  1191. sep='newline',
  1192. quiet=True)
  1193. if not mapsets:
  1194. fatal(_("Unable to list mapsets"))
  1195. return mapsets.splitlines()
  1196. # interface to `g.proj -c`
  1197. def create_location(dbase, location, epsg=None, proj4=None, filename=None,
  1198. wkt=None, datum=None, datum_trans=None, desc=None, overwrite=False):
  1199. """!Create new location
  1200. Raise ScriptError on error.
  1201. @param dbase path to GRASS database
  1202. @param location location name to create
  1203. @param epsg if given create new location based on EPSG code
  1204. @param proj4 if given create new location based on Proj4 definition
  1205. @param filename if given create new location based on georeferenced file
  1206. @param wkt if given create new location based on WKT definition (path to PRJ file)
  1207. @param datum GRASS format datum code
  1208. @param datum_trans datum transformation parameters (used for epsg and proj4)
  1209. @param desc description of the location (creates MYNAME file)
  1210. @param overwrite True to overwrite location if exists (WARNING: ALL DATA from existing location ARE DELETED!)
  1211. """
  1212. gisdbase = None
  1213. if epsg or proj4 or filename or wkt:
  1214. # FIXME: changing GISDBASE mid-session is not background-job safe
  1215. gisdbase = gisenv()['GISDBASE']
  1216. run_command('g.gisenv', set='GISDBASE=%s' % dbase)
  1217. # create dbase if not exists
  1218. if not os.path.exists(dbase):
  1219. os.mkdir(dbase)
  1220. # check if location already exists
  1221. if os.path.exists(os.path.join(dbase, location)):
  1222. if not overwrite:
  1223. warning(_("Location <%s> already exists. Operation canceled.") % location)
  1224. return
  1225. else:
  1226. warning(_("Location <%s> already exists and will be overwritten") % location)
  1227. shutil.rmtree(os.path.join(dbase, location))
  1228. kwargs = dict()
  1229. if datum:
  1230. kwargs['datum'] = datum
  1231. if datum_trans:
  1232. kwargs['datum_trans'] = datum_trans
  1233. if epsg:
  1234. ps = pipe_command('g.proj', quiet=True, flags='t', epsg=epsg,
  1235. location=location, stderr=PIPE, **kwargs)
  1236. elif proj4:
  1237. ps = pipe_command('g.proj', quiet=True, flags='t', proj4=proj4,
  1238. location=location, stderr=PIPE, **kwargs)
  1239. elif filename:
  1240. ps = pipe_command('g.proj', quiet=True, georef=filename,
  1241. location=location, stderr=PIPE)
  1242. elif wkt:
  1243. ps = pipe_command('g.proj', quiet=True, wkt=wkt, location=location,
  1244. stderr=PIPE)
  1245. else:
  1246. _create_location_xy(dbase, location)
  1247. if epsg or proj4 or filename or wkt:
  1248. error = ps.communicate()[1]
  1249. run_command('g.gisenv', set='GISDBASE=%s' % gisdbase)
  1250. if ps.returncode != 0 and error:
  1251. raise ScriptError(repr(error))
  1252. try:
  1253. fd = codecs.open(os.path.join(dbase, location, 'PERMANENT', 'MYNAME'),
  1254. encoding='utf-8', mode='w')
  1255. if desc:
  1256. fd.write(desc + os.linesep)
  1257. else:
  1258. fd.write(os.linesep)
  1259. fd.close()
  1260. except OSError as e:
  1261. raise ScriptError(repr(e))
  1262. def _create_location_xy(database, location):
  1263. """!Create unprojected location
  1264. Raise ScriptError on error.
  1265. @param database GRASS database where to create new location
  1266. @param location location name
  1267. """
  1268. cur_dir = os.getcwd()
  1269. try:
  1270. os.chdir(database)
  1271. os.mkdir(location)
  1272. os.mkdir(os.path.join(location, 'PERMANENT'))
  1273. # create DEFAULT_WIND and WIND files
  1274. regioninfo = ['proj: 0',
  1275. 'zone: 0',
  1276. 'north: 1',
  1277. 'south: 0',
  1278. 'east: 1',
  1279. 'west: 0',
  1280. 'cols: 1',
  1281. 'rows: 1',
  1282. 'e-w resol: 1',
  1283. 'n-s resol: 1',
  1284. 'top: 1',
  1285. 'bottom: 0',
  1286. 'cols3: 1',
  1287. 'rows3: 1',
  1288. 'depths: 1',
  1289. 'e-w resol3: 1',
  1290. 'n-s resol3: 1',
  1291. 't-b resol: 1']
  1292. defwind = open(os.path.join(location,
  1293. "PERMANENT", "DEFAULT_WIND"), 'w')
  1294. for param in regioninfo:
  1295. defwind.write(param + '%s' % os.linesep)
  1296. defwind.close()
  1297. shutil.copy(os.path.join(location, "PERMANENT", "DEFAULT_WIND"),
  1298. os.path.join(location, "PERMANENT", "WIND"))
  1299. os.chdir(cur_dir)
  1300. except OSError as e:
  1301. raise ScriptError(repr(e))
  1302. # interface to g.version
  1303. def version():
  1304. """!Get GRASS version as dictionary
  1305. @code
  1306. print version()
  1307. {'proj4': '4.8.0', 'geos': '3.3.5', 'libgis_revision': '52468',
  1308. 'libgis_date': '2012-07-27 22:53:30 +0200 (Fri, 27 Jul 2012)',
  1309. 'version': '7.0.svn', 'date': '2012', 'gdal': '2.0dev',
  1310. 'revision': '53670'}
  1311. @endcode
  1312. """
  1313. data = parse_command('g.version', flags='rge')
  1314. for k, v in data.iteritems():
  1315. data[k.strip()] = v.replace('"', '').strip()
  1316. return data
  1317. # get debug_level
  1318. _debug_level = None
  1319. def debug_level():
  1320. global _debug_level
  1321. if _debug_level is not None:
  1322. return _debug_level
  1323. _debug_level = 0
  1324. if find_program('g.gisenv', '--help'):
  1325. _debug_level = int(gisenv().get('DEBUG', 0))
  1326. def legal_name(s):
  1327. """!Checks if the string contains only allowed characters.
  1328. This is the Python implementation of G_legal_filename() function.
  1329. @note It is not clear when to use this function.
  1330. """
  1331. if not s or s[0] == '.':
  1332. warning(_("Illegal filename <%s>. Cannot be 'NULL' or start with " \
  1333. "'.'.") % s)
  1334. return False
  1335. illegal = [c
  1336. for c in s
  1337. if c in '/"\'@,=*~' or c <= ' ' or c >= '\177']
  1338. if illegal:
  1339. illegal = ''.join(sorted(set(illegal)))
  1340. warning(_("Illegal filename <%(s)s>. <%(il)s> not allowed.\n") % {
  1341. 's': s, 'il': illegal})
  1342. return False
  1343. return True
  1344. if __name__ == '__main__':
  1345. import doctest
  1346. doctest.testmod()