core.py 47 KB

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