core.py 47 KB

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