core.py 50 KB

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