core.py 47 KB

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