core.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487
  1. """
  2. Core functions to be used in Python scripts.
  3. Usage:
  4. ::
  5. from grass.script import core as grass
  6. grass.parser()
  7. (C) 2008-2014 by the GRASS Development Team
  8. This program is free software under the GNU General Public
  9. License (>=v2). Read the file COPYING that comes with GRASS
  10. for details.
  11. .. sectionauthor:: Glynn Clements
  12. .. sectionauthor:: Martin Landa <landa.martin gmail.com>
  13. .. sectionauthor:: Michael Barton <michael.barton asu.edu>
  14. """
  15. import os
  16. import sys
  17. import types
  18. import re
  19. import atexit
  20. import subprocess
  21. import shutil
  22. import codecs
  23. import types as python_types
  24. from utils import KeyValue, parse_key_val, basename, encode
  25. from grass.exceptions import ScriptError
  26. # i18N
  27. import gettext
  28. gettext.install('grasslibs', os.path.join(os.getenv("GISBASE"), 'locale'))
  29. # subprocess wrapper that uses shell on Windows
  30. class Popen(subprocess.Popen):
  31. _builtin_exts = set(['.com', '.exe', '.bat', '.cmd'])
  32. @staticmethod
  33. def _escape_for_shell(arg):
  34. # TODO: what are cmd.exe's parsing rules?
  35. return arg
  36. def __init__(self, args, **kwargs):
  37. if (sys.platform == 'win32'
  38. and isinstance(args, list)
  39. and not kwargs.get('shell', False)
  40. and kwargs.get('executable') is None):
  41. cmd = shutil_which(args[0])
  42. if cmd is None:
  43. raise OSError
  44. args = [cmd] + args[1:]
  45. name, ext = os.path.splitext(cmd)
  46. if ext.lower() not in self._builtin_exts:
  47. kwargs['shell'] = True
  48. args = [self._escape_for_shell(arg) for arg in args]
  49. subprocess.Popen.__init__(self, args, **kwargs)
  50. PIPE = subprocess.PIPE
  51. STDOUT = subprocess.STDOUT
  52. raise_on_error = False # raise exception instead of calling fatal()
  53. def call(*args, **kwargs):
  54. return Popen(*args, **kwargs).wait()
  55. # GRASS-oriented interface to subprocess module
  56. _popen_args = ["bufsize", "executable", "stdin", "stdout", "stderr",
  57. "preexec_fn", "close_fds", "cwd", "env",
  58. "universal_newlines", "startupinfo", "creationflags"]
  59. def _make_val(val):
  60. if isinstance(val, types.StringType) or \
  61. isinstance(val, types.UnicodeType):
  62. return val
  63. if isinstance(val, types.ListType):
  64. return ",".join(map(_make_val, val))
  65. if isinstance(val, types.TupleType):
  66. return _make_val(list(val))
  67. return str(val)
  68. def get_commands():
  69. """Create list of available GRASS commands to use when parsing
  70. string from the command line
  71. :return: list of commands (set) and directory of scripts (collected
  72. by extension - MS Windows only)
  73. >>> cmds = list(get_commands()[0])
  74. >>> cmds.sort()
  75. >>> cmds[:5]
  76. ['d.barscale', 'd.colorlist', 'd.colortable', 'd.correlate', 'd.erase']
  77. """
  78. gisbase = os.environ['GISBASE']
  79. cmd = list()
  80. scripts = {'.py': list()} if sys.platform == 'win32' else {}
  81. def scan(gisbase, directory):
  82. dir_path = os.path.join(gisbase, directory)
  83. if os.path.exists(dir_path):
  84. for fname in os.listdir(os.path.join(gisbase, directory)):
  85. if scripts: # win32
  86. name, ext = os.path.splitext(fname)
  87. if ext != '.manifest':
  88. cmd.append(name)
  89. if ext in scripts.keys():
  90. scripts[ext].append(name)
  91. else:
  92. cmd.append(fname)
  93. for directory in ('bin', 'scripts'):
  94. scan(gisbase, directory)
  95. # scan gui/scripts/
  96. gui_path = os.path.join(gisbase, 'etc', 'gui', 'scripts')
  97. if os.path.exists(gui_path):
  98. os.environ["PATH"] = os.getenv("PATH") + os.pathsep + gui_path
  99. cmd = cmd + os.listdir(gui_path)
  100. return set(cmd), scripts
  101. # replacement for which function from shutil (not available in all versions)
  102. # from http://hg.python.org/cpython/file/6860263c05b3/Lib/shutil.py#l1068
  103. # added because of Python scripts running Python scripts on MS Windows
  104. # see also ticket #2008 which is unrelated but same function was proposed
  105. def shutil_which(cmd, mode=os.F_OK | os.X_OK, path=None):
  106. """Given a command, mode, and a PATH string, return the path which
  107. conforms to the given mode on the PATH, or None if there is no such
  108. file.
  109. `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
  110. of os.environ.get("PATH"), or can be overridden with a custom search
  111. path.
  112. :param cmd: the command
  113. :param mode:
  114. :param path:
  115. """
  116. # Check that a given file can be accessed with the correct mode.
  117. # Additionally check that `file` is not a directory, as on Windows
  118. # directories pass the os.access check.
  119. def _access_check(fn, mode):
  120. return (os.path.exists(fn) and os.access(fn, mode)
  121. and not os.path.isdir(fn))
  122. # If we're given a path with a directory part, look it up directly rather
  123. # than referring to PATH directories. This includes checking relative to the
  124. # current directory, e.g. ./script
  125. if os.path.dirname(cmd):
  126. if _access_check(cmd, mode):
  127. return cmd
  128. return None
  129. if path is None:
  130. path = os.environ.get("PATH", os.defpath)
  131. if not path:
  132. return None
  133. path = path.split(os.pathsep)
  134. if sys.platform == "win32":
  135. # The current directory takes precedence on Windows.
  136. if not os.curdir in path:
  137. path.insert(0, os.curdir)
  138. # PATHEXT is necessary to check on Windows.
  139. pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
  140. map(lambda x: x.lower(), pathext) # force lowercase
  141. if '.py' not in pathext: # we assume that PATHEXT contains always '.py'
  142. pathext.insert(0, '.py')
  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. :param cmd: the command
  190. """
  191. if sys.platform == 'win32':
  192. # we in fact expect pure module name (without extension)
  193. # so, lets remove extension
  194. if os.path.splitext(cmd)[1] == '.py':
  195. cmd = cmd[:-3]
  196. full_path = shutil_which(cmd + '.py')
  197. if full_path:
  198. return full_path
  199. return cmd
  200. def make_command(prog, flags="", overwrite=False, quiet=False, verbose=False,
  201. **options):
  202. """Return a list of strings suitable for use as the args parameter to
  203. Popen() or call(). Example:
  204. >>> make_command("g.message", flags = 'w', message = 'this is a warning')
  205. ['g.message', '-w', 'message=this is a warning']
  206. :param str prog: GRASS module
  207. :param str flags: flags to be used (given as a string)
  208. :param bool overwrite: True to enable overwriting the output (<tt>--o</tt>)
  209. :param bool quiet: True to run quietly (<tt>--q</tt>)
  210. :param bool verbose: True to run verbosely (<tt>--v</tt>)
  211. :param options: module's parameters
  212. :return: list of arguments
  213. """
  214. args = [prog]
  215. if overwrite:
  216. args.append("--o")
  217. if quiet:
  218. args.append("--q")
  219. if verbose:
  220. args.append("--v")
  221. if flags:
  222. if '-' in flags:
  223. raise ScriptError("'-' is not a valid flag")
  224. args.append("-%s" % flags)
  225. for opt, val in options.iteritems():
  226. if val != None:
  227. if opt.startswith('_'):
  228. opt = opt[1:]
  229. warning(_("To run the module add underscore at the end"
  230. " of the option <%s> to avoid conflict with Python"
  231. " keywords. Underscore at the beginning is"
  232. " depreciated in GRASS GIS 7.0 and will be removed"
  233. " in version 7.1.") % opt)
  234. elif opt.endswith('_'):
  235. opt = opt[:-1]
  236. args.append("%s=%s" % (opt, _make_val(val)))
  237. return args
  238. def start_command(prog, flags="", overwrite=False, quiet=False,
  239. verbose=False, **kwargs):
  240. """Returns a Popen object with the command created by make_command.
  241. Accepts any of the arguments which Popen() accepts apart from "args"
  242. and "shell".
  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. If the module parameter is the same as Python keyword, add
  254. underscore at the end of the parameter. For example, use
  255. ``lambda_=1.6`` instead of ``lambda=1.6``.
  256. :param str prog: GRASS module
  257. :param str flags: flags to be used (given as a string)
  258. :param bool overwrite: True to enable overwriting the output (<tt>--o</tt>)
  259. :param bool quiet: True to run quietly (<tt>--q</tt>)
  260. :param bool verbose: True to run verbosely (<tt>--v</tt>)
  261. :param kwargs: module's parameters
  262. :return: Popen object
  263. """
  264. options = {}
  265. popts = {}
  266. for opt, val in kwargs.iteritems():
  267. if opt in _popen_args:
  268. popts[opt] = val
  269. else:
  270. if isinstance(val, unicode):
  271. val = encode(val)
  272. options[opt] = val
  273. args = make_command(prog, flags, overwrite, quiet, verbose, **options)
  274. if debug_level() > 0:
  275. sys.stderr.write("D1/%d: %s.start_command(): %s\n" % (debug_level(),
  276. __name__,
  277. ' '.join(args)))
  278. sys.stderr.flush()
  279. return Popen(args, **popts)
  280. def run_command(*args, **kwargs):
  281. """Passes all arguments to start_command(), then waits for the process to
  282. complete, returning its exit code. Similar to subprocess.call(), but
  283. with the make_command() interface.
  284. :param list args: list of unnamed arguments (see start_command() for details)
  285. :param list kwargs: list of named arguments (see start_command() for details)
  286. :return: exit code (0 for success)
  287. """
  288. ps = start_command(*args, **kwargs)
  289. return ps.wait()
  290. def pipe_command(*args, **kwargs):
  291. """Passes all arguments to start_command(), but also adds
  292. "stdout = PIPE". Returns the Popen object.
  293. >>> p = pipe_command("g.gisenv")
  294. >>> print p # doctest: +ELLIPSIS
  295. <....Popen object at 0x...>
  296. >>> print p.communicate()[0] # doctest: +SKIP
  297. GISDBASE='/opt/grass-data';
  298. LOCATION_NAME='spearfish60';
  299. MAPSET='glynn';
  300. GRASS_DB_ENCODING='ascii';
  301. GUI='text';
  302. MONITOR='x0';
  303. :param list args: list of unnamed arguments (see start_command() for details)
  304. :param list 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 list args: list of unnamed arguments (see start_command() for details)
  313. :param list 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 list args: list of unnamed arguments (see start_command() for details)
  322. :param list 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. ::
  333. parse_command(..., parse = (grass.parse_key_val, { 'sep' : ':' }))
  334. or you can simply define <em>delimiter</em>
  335. ::
  336. parse_command(..., delimiter = ':')
  337. :param args: list of unnamed arguments (see start_command() for details)
  338. :param kwargs: list of named arguments (see start_command() for details)
  339. :return: parsed module output
  340. """
  341. parse = None
  342. parse_args = {}
  343. if 'parse' in kwargs:
  344. if type(kwargs['parse']) is types.TupleType:
  345. parse = kwargs['parse'][0]
  346. parse_args = kwargs['parse'][1]
  347. del kwargs['parse']
  348. if 'delimiter' in kwargs:
  349. parse_args = {'sep': kwargs['delimiter']}
  350. del kwargs['delimiter']
  351. if not parse:
  352. parse = parse_key_val # use default fn
  353. res = read_command(*args, **kwargs)
  354. return parse(res, **parse_args)
  355. def write_command(*args, **kwargs):
  356. """Passes all arguments to feed_command, with the string specified
  357. by the 'stdin' argument fed to the process' stdin.
  358. :param list args: list of unnamed arguments (see start_command() for details)
  359. :param list kwargs: list of named arguments (see start_command() for details)
  360. :return: return code
  361. """
  362. stdin = kwargs['stdin']
  363. p = feed_command(*args, **kwargs)
  364. p.stdin.write(stdin)
  365. p.stdin.close()
  366. return p.wait()
  367. def exec_command(prog, flags="", overwrite=False, quiet=False, verbose=False,
  368. env=None, **kwargs):
  369. """Interface to os.execvpe(), but with the make_command() interface.
  370. :param str prog: GRASS module
  371. :param str flags: flags to be used (given as a string)
  372. :param bool overwrite: True to enable overwriting the output (<tt>--o</tt>)
  373. :param bool quiet: True to run quietly (<tt>--q</tt>)
  374. :param bool verbose: True to run verbosely (<tt>--v</tt>)
  375. :param env: directory with environmental variables
  376. :param list kwargs: module's parameters
  377. """
  378. args = make_command(prog, flags, overwrite, quiet, verbose, **kwargs)
  379. if env is None:
  380. env = os.environ
  381. os.execvpe(prog, args, env)
  382. # interface to g.message
  383. def message(msg, flag=None):
  384. """Display a message using `g.message`
  385. :param str msg: message to be displayed
  386. :param str flag: flags (given as string)
  387. """
  388. run_command("g.message", flags=flag, message=msg)
  389. def debug(msg, debug=1):
  390. """Display a debugging message using `g.message -d`
  391. :param str msg: debugging message to be displayed
  392. :param str debug: debug level (0-5)
  393. """
  394. if debug_level() >= debug:
  395. if sys.platform == "win32":
  396. msg = msg.replace('&', '^&')
  397. run_command("g.message", flags='d', message=msg, debug=debug)
  398. def verbose(msg):
  399. """Display a verbose message using `g.message -v`
  400. :param str msg: verbose message to be displayed
  401. """
  402. message(msg, flag='v')
  403. def info(msg):
  404. """Display an informational message using `g.message -i`
  405. :param str msg: informational message to be displayed
  406. """
  407. message(msg, flag='i')
  408. def percent(i, n, s):
  409. """Display a progress info message using `g.message -p`
  410. ::
  411. message(_("Percent complete..."))
  412. n = 100
  413. for i in range(n):
  414. percent(i, n, 1)
  415. percent(1, 1, 1)
  416. :param int i: current item
  417. :param int n: total number of items
  418. :param int 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 str 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 str 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 str 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 bool 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. ::
  480. if __name__ == "__main__":
  481. options, flags = grass.parser()
  482. main()
  483. Thereafter, the global variables "options" and "flags" will be
  484. dictionaries containing option/flag values, keyed by lower-case
  485. option/flag names. The values in "options" are strings, those in
  486. "flags" are Python booleans.
  487. """
  488. if not os.getenv("GISBASE"):
  489. print >> sys.stderr, "You must be in GRASS GIS to run this program."
  490. sys.exit(1)
  491. cmdline = [basename(sys.argv[0])]
  492. cmdline += ['"' + arg + '"' for arg in sys.argv[1:]]
  493. os.environ['CMDLINE'] = ' '.join(cmdline)
  494. argv = sys.argv[:]
  495. name = argv[0]
  496. if not os.path.isabs(name):
  497. if os.sep in name or (os.altsep and os.altsep in name):
  498. argv[0] = os.path.abspath(name)
  499. else:
  500. argv[0] = os.path.join(sys.path[0], name)
  501. prog = "g.parser.exe" if sys.platform == "win32" else "g.parser"
  502. p = subprocess.Popen([prog, '-n'] + argv, stdout=subprocess.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 g.tempfile.
  512. :param bool create: True to create a file
  513. :return: path to a tmp file
  514. """
  515. flags = ''
  516. if not create:
  517. flags += 'd'
  518. return read_command("g.tempfile", flags=flags, pid=os.getpid()).strip()
  519. def tempdir():
  520. """Returns the name of a temporary dir, created with g.tempfile."""
  521. tmp = tempfile(create=False)
  522. os.mkdir(tmp)
  523. return tmp
  524. def _compare_projection(dic):
  525. """Check if projection has some possibility of duplicate names like
  526. Universal Transverse Mercator and Universe Transverse Mercator and
  527. unify them
  528. :param dic: The dictionary containing information about projection
  529. :return: The dictionary with the new values if needed
  530. """
  531. # the lookup variable is a list of list, each list contains all the
  532. # possible name for a projection system
  533. lookup = [['Universal Transverse Mercator', 'Universe Transverse Mercator']]
  534. for lo in lookup:
  535. for n in range(len(dic['name'])):
  536. if dic['name'][n] in lo:
  537. dic['name'][n] = lo[0]
  538. return dic
  539. def _compare_units(dic):
  540. """Check if units has some possibility of duplicate names like
  541. meter and metre and unify them
  542. :param dic: The dictionary containing information about units
  543. :return: The dictionary with the new values if needed
  544. """
  545. # the lookup variable is a list of list, each list contains all the
  546. # possible name for a units
  547. lookup = [['meter', 'metre'], ['meters', 'metres'], ['kilometer',
  548. 'kilometre'], ['kilometers', 'kilometres']]
  549. for l in lookup:
  550. for n in range(len(dic['unit'])):
  551. if dic['unit'][n].lower() in l:
  552. dic['unit'][n] = l[0]
  553. for n in range(len(dic['units'])):
  554. if dic['units'][n].lower() in l:
  555. dic['units'][n] = l[0]
  556. return dic
  557. def _text_to_key_value_dict(filename, sep=":", val_sep=",", checkproj=False,
  558. checkunits=False):
  559. """Convert a key-value text file, where entries are separated by newlines
  560. and the key and value are separated by `sep', into a key-value dictionary
  561. and discover/use the correct data types (float, int or string) for values.
  562. :param str filename: The name or name and path of the text file to convert
  563. :param str sep: The character that separates the keys and values, default
  564. is ":"
  565. :param str val_sep: The character that separates the values of a single
  566. key, default is ","
  567. :param bool checkproj: True if it has to check some information about
  568. projection system
  569. :param bool checkproj: True if it has to check some information about units
  570. :return: The dictionary
  571. A text file with this content:
  572. ::
  573. a: Hello
  574. b: 1.0
  575. c: 1,2,3,4,5
  576. d : hello,8,0.1
  577. Will be represented as this dictionary:
  578. ::
  579. {'a': ['Hello'], 'c': [1, 2, 3, 4, 5], 'b': [1.0], 'd': ['hello', 8, 0.1]}
  580. """
  581. text = open(filename, "r").readlines()
  582. kvdict = KeyValue()
  583. for line in text:
  584. if line.find(sep) >= 0:
  585. key, value = line.split(sep)
  586. key = key.strip()
  587. value = value.strip()
  588. else:
  589. # Jump over empty values
  590. continue
  591. values = value.split(val_sep)
  592. value_list = []
  593. for value in values:
  594. not_float = False
  595. not_int = False
  596. # Convert values into correct types
  597. # We first try integer then float
  598. try:
  599. value_converted = int(value)
  600. except:
  601. not_int = True
  602. if not_int:
  603. try:
  604. value_converted = float(value)
  605. except:
  606. not_float = True
  607. if not_int and not_float:
  608. value_converted = value.strip()
  609. value_list.append(value_converted)
  610. kvdict[key] = value_list
  611. if checkproj:
  612. kvdict = _compare_projection(kvdict)
  613. if checkunits:
  614. kvdict = _compare_units(kvdict)
  615. return kvdict
  616. def compare_key_value_text_files(filename_a, filename_b, sep=":",
  617. val_sep=",", precision=0.000001,
  618. proj=False, units=False):
  619. """Compare two key-value text files
  620. This method will print a warning in case keys that are present in the first
  621. file are not present in the second one.
  622. The comparison method tries to convert the values into their native format
  623. (float, int or string) to allow correct comparison.
  624. An example key-value text file may have this content:
  625. ::
  626. a: Hello
  627. b: 1.0
  628. c: 1,2,3,4,5
  629. d : hello,8,0.1
  630. :param str filename_a: name of the first key-value text file
  631. :param str filenmae_b: name of the second key-value text file
  632. :param str sep: character that separates the keys and values, default is ":"
  633. :param str val_sep: character that separates the values of a single key, default is ","
  634. :param double precision: precision with which the floating point values are compared
  635. :param bool proj: True if it has to check some information about projection system
  636. :param bool units: True if it has to check some information about units
  637. :return: True if full or almost identical, False if different
  638. """
  639. dict_a = _text_to_key_value_dict(filename_a, sep, checkproj=proj,
  640. checkunits=units)
  641. dict_b = _text_to_key_value_dict(filename_b, sep, checkproj=proj,
  642. checkunits=units)
  643. if sorted(dict_a.keys()) != sorted(dict_b.keys()):
  644. return False
  645. # We compare matching keys
  646. for key in dict_a.keys():
  647. # Floating point values must be handled separately
  648. if isinstance(dict_a[key], float) and isinstance(dict_b[key], float):
  649. if abs(dict_a[key] - dict_b[key]) > precision:
  650. return False
  651. elif isinstance(dict_a[key], float) or isinstance(dict_b[key], float):
  652. warning(_("Mixing value types. Will try to compare after "
  653. "integer conversion"))
  654. return int(dict_a[key]) == int(dict_b[key])
  655. elif key == "+towgs84":
  656. # We compare the sum of the entries
  657. if abs(sum(dict_a[key]) - sum(dict_b[key])) > precision:
  658. return False
  659. else:
  660. if dict_a[key] != dict_b[key]:
  661. return False
  662. return True
  663. # interface to g.gisenv
  664. def gisenv():
  665. """Returns the output from running g.gisenv (with no arguments), as a
  666. dictionary. Example:
  667. >>> env = gisenv()
  668. >>> print env['GISDBASE'] # doctest: +SKIP
  669. /opt/grass-data
  670. :return: list of GRASS variables
  671. """
  672. s = read_command("g.gisenv", flags='n')
  673. return parse_key_val(s)
  674. # interface to g.region
  675. def locn_is_latlong():
  676. """Tests if location is lat/long. Value is obtained
  677. by checking the "g.region -pu" projection code.
  678. :return: True for a lat/long region, False otherwise
  679. """
  680. s = read_command("g.region", flags='pu')
  681. kv = parse_key_val(s, ':')
  682. if kv['projection'].split(' ')[0] == '3':
  683. return True
  684. else:
  685. return False
  686. def region(region3d=False, complete=False):
  687. """Returns the output from running "g.region -gu", as a
  688. dictionary. Example:
  689. :param bool region3d: True to get 3D region
  690. :param bool complete:
  691. >>> curent_region = region()
  692. >>> # obtain n, s, e and w values
  693. >>> [curent_region[key] for key in "nsew"] # doctest: +ELLIPSIS
  694. [..., ..., ..., ...]
  695. >>> # obtain ns and ew resulutions
  696. >>> (curent_region['nsres'], curent_region['ewres']) # doctest: +ELLIPSIS
  697. (..., ...)
  698. :return: dictionary of region values
  699. """
  700. flgs = 'gu'
  701. if region3d:
  702. flgs += '3'
  703. if complete:
  704. flgs += 'cep'
  705. s = read_command("g.region", flags=flgs)
  706. reg = parse_key_val(s, val_type=float)
  707. for k in ['rows', 'cols', 'cells',
  708. 'rows3', 'cols3', 'cells3', 'depths']:
  709. if k not in reg:
  710. continue
  711. reg[k] = int(reg[k])
  712. return reg
  713. def region_env(region3d=False, **kwargs):
  714. """Returns region settings as a string which can used as
  715. GRASS_REGION environmental variable.
  716. If no 'kwargs' are given then the current region is used. Note
  717. that this function doesn't modify the current region!
  718. See also use_temp_region() for alternative method how to define
  719. temporary region used for raster-based computation.
  720. :param bool region3d: True to get 3D region
  721. :param kwargs: g.region's parameters like 'rast', 'vect' or 'region'
  722. ::
  723. os.environ['GRASS_REGION'] = grass.region_env(region='detail')
  724. grass.mapcalc('map=1', overwrite=True)
  725. os.environ.pop('GRASS_REGION')
  726. :return: string with region values
  727. :return: empty string on error
  728. """
  729. # read proj/zone from WIND file
  730. env = gisenv()
  731. windfile = os.path.join(env['GISDBASE'], env['LOCATION_NAME'],
  732. env['MAPSET'], "WIND")
  733. fd = open(windfile, "r")
  734. grass_region = ''
  735. for line in fd.readlines():
  736. key, value = map(lambda x: x.strip(), line.split(":", 1))
  737. if kwargs and key not in ('proj', 'zone'):
  738. continue
  739. if not kwargs and not region3d and \
  740. key in ('top', 'bottom', 'cols3', 'rows3',
  741. 'depths', 'e-w resol3', 'n-s resol3', 't-b resol'):
  742. continue
  743. grass_region += '%s: %s;' % (key, value)
  744. if not kwargs: # return current region
  745. return grass_region
  746. # read other values from `g.region -gu`
  747. flgs = 'ug'
  748. if region3d:
  749. flgs += '3'
  750. s = read_command('g.region', flags=flgs, **kwargs)
  751. if not s:
  752. return ''
  753. reg = parse_key_val(s)
  754. kwdata = [('north', 'n'),
  755. ('south', 's'),
  756. ('east', 'e'),
  757. ('west', 'w'),
  758. ('cols', 'cols'),
  759. ('rows', 'rows'),
  760. ('e-w resol', 'ewres'),
  761. ('n-s resol', 'nsres')]
  762. if region3d:
  763. kwdata += [('top', 't'),
  764. ('bottom', 'b'),
  765. ('cols3', 'cols3'),
  766. ('rows3', 'rows3'),
  767. ('depths', 'depths'),
  768. ('e-w resol3', 'ewres3'),
  769. ('n-s resol3', 'nsres3'),
  770. ('t-b resol', 'tbres')]
  771. for wkey, rkey in kwdata:
  772. grass_region += '%s: %s;' % (wkey, reg[rkey])
  773. return grass_region
  774. def use_temp_region():
  775. """Copies the current region to a temporary region with "g.region save=",
  776. then sets WIND_OVERRIDE to refer to that region. Installs an atexit
  777. handler to delete the temporary region upon termination.
  778. """
  779. name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
  780. run_command("g.region", save=name, overwrite=True)
  781. os.environ['WIND_OVERRIDE'] = name
  782. atexit.register(del_temp_region)
  783. def del_temp_region():
  784. """Unsets WIND_OVERRIDE and removes any region named by it."""
  785. try:
  786. name = os.environ.pop('WIND_OVERRIDE')
  787. run_command("g.remove", flags='f', quiet=True, type='region', name=name)
  788. except:
  789. pass
  790. # interface to g.findfile
  791. def find_file(name, element='cell', mapset=None):
  792. """Returns the output from running g.findfile as a
  793. dictionary. Example:
  794. >>> result = find_file('elevation', element='cell')
  795. >>> print result['fullname']
  796. elevation@PERMANENT
  797. >>> print result['file'] # doctest: +ELLIPSIS
  798. /.../PERMANENT/cell/elevation
  799. :param str name: file name
  800. :param str element: element type (default 'cell')
  801. :param str mapset: mapset name (default all mapsets in search path)
  802. :return: parsed output of g.findfile
  803. """
  804. if element == 'raster' or element == 'rast':
  805. verbose(_('Element type should be "cell" and not "%s"') % element)
  806. element = 'cell'
  807. s = read_command("g.findfile", flags='n', element=element, file=name,
  808. mapset=mapset)
  809. return parse_key_val(s)
  810. # interface to g.list
  811. def list_strings(type, pattern=None, mapset=None, exclude=None, flag=''):
  812. """List of elements as strings.
  813. Returns the output from running g.list, as a list of qualified
  814. names.
  815. :param str type: element type (rast, vect, rast3d, region, ...)
  816. :param str pattern: pattern string
  817. :param str mapset: mapset name (if not given use search path)
  818. :param str exclude: pattern string to exclude maps from the research
  819. :param str flag: pattern type: 'r' (basic regexp), 'e' (extended regexp),
  820. or '' (glob pattern)
  821. :return: list of elements
  822. """
  823. if type == 'raster' or type == 'cell':
  824. verbose(_('Element type should be "rast" and not "%s"') % type)
  825. type = 'rast'
  826. result = list()
  827. for line in read_command("g.list",
  828. quiet=True,
  829. flags='m' + flag,
  830. type=type,
  831. pattern=pattern,
  832. exclude=exclude,
  833. mapset=mapset).splitlines():
  834. result.append(line.strip())
  835. return result
  836. def list_pairs(type, pattern=None, mapset=None, exclude=None, flag=''):
  837. """List of elements as pairs
  838. Returns the output from running g.list, as a list of
  839. (name, mapset) pairs
  840. :param str type: element type (rast, vect, rast3d, region, ...)
  841. :param str pattern: pattern string
  842. :param str mapset: mapset name (if not given use search path)
  843. :param str exclude: pattern string to exclude maps from the research
  844. :param str flag: pattern type: 'r' (basic regexp), 'e' (extended regexp),
  845. or '' (glob pattern)
  846. :return: list of elements
  847. """
  848. return [tuple(map.split('@', 1)) for map in list_strings(type, pattern,
  849. mapset, exclude,
  850. flag)]
  851. def list_grouped(type, pattern=None, check_search_path=True, exclude=None,
  852. flag=''):
  853. """List of elements grouped by mapsets.
  854. Returns the output from running g.list, as a dictionary where the
  855. keys are mapset names and the values are lists of maps in that
  856. mapset. Example:
  857. >>> list_grouped('vect', pattern='*roads*')['PERMANENT']
  858. ['railroads', 'roadsmajor']
  859. :param str type: element type (rast, vect, rast3d, region, ...) or list of elements
  860. :param str pattern: pattern string
  861. :param str check_search_path: True to add mapsets for the search path
  862. with no found elements
  863. :param str exclude: pattern string to exclude maps from the research
  864. :param str flag: pattern type: 'r' (basic regexp), 'e' (extended regexp),
  865. or '' (glob pattern)
  866. :return: directory of mapsets/elements
  867. """
  868. if isinstance(type, python_types.StringTypes) or len(type) == 1:
  869. types = [type]
  870. store_types = False
  871. else:
  872. types = type
  873. store_types = True
  874. flag += 't'
  875. for i in range(len(types)):
  876. if types[i] == 'raster' or types[i] == 'cell':
  877. verbose(_('Element type should be "rast" and not "%s"') % types[i])
  878. types[i] = 'rast'
  879. result = {}
  880. if check_search_path:
  881. for mapset in mapsets(search_path=True):
  882. if store_types:
  883. result[mapset] = {}
  884. else:
  885. result[mapset] = []
  886. mapset = None
  887. for line in read_command("g.list", quiet=True, flags="m" + flag,
  888. type=types, pattern=pattern, exclude=exclude).splitlines():
  889. try:
  890. name, mapset = line.split('@')
  891. except ValueError:
  892. warning(_("Invalid element '%s'") % line)
  893. continue
  894. if store_types:
  895. type_, name = name.split('/')
  896. if mapset in result:
  897. if type_ in result[mapset]:
  898. result[mapset][type_].append(name)
  899. else:
  900. result[mapset][type_] = [name, ]
  901. else:
  902. result[mapset] = {type_: [name, ]}
  903. else:
  904. if mapset in result:
  905. result[mapset].append(name)
  906. else:
  907. result[mapset] = [name, ]
  908. return result
  909. # color parsing
  910. named_colors = {
  911. "white": (1.00, 1.00, 1.00),
  912. "black": (0.00, 0.00, 0.00),
  913. "red": (1.00, 0.00, 0.00),
  914. "green": (0.00, 1.00, 0.00),
  915. "blue": (0.00, 0.00, 1.00),
  916. "yellow": (1.00, 1.00, 0.00),
  917. "magenta": (1.00, 0.00, 1.00),
  918. "cyan": (0.00, 1.00, 1.00),
  919. "aqua": (0.00, 0.75, 0.75),
  920. "grey": (0.75, 0.75, 0.75),
  921. "gray": (0.75, 0.75, 0.75),
  922. "orange": (1.00, 0.50, 0.00),
  923. "brown": (0.75, 0.50, 0.25),
  924. "purple": (0.50, 0.00, 1.00),
  925. "violet": (0.50, 0.00, 1.00),
  926. "indigo": (0.00, 0.50, 1.00)}
  927. def parse_color(val, dflt=None):
  928. """Parses the string "val" as a GRASS colour, which can be either one of
  929. the named colours or an R:G:B tuple e.g. 255:255:255. Returns an
  930. (r,g,b) triple whose components are floating point values between 0
  931. and 1. Example:
  932. >>> parse_color("red")
  933. (1.0, 0.0, 0.0)
  934. >>> parse_color("255:0:0")
  935. (1.0, 0.0, 0.0)
  936. :param val: color value
  937. :param dflt: default color value
  938. :return: tuple RGB
  939. """
  940. if val in named_colors:
  941. return named_colors[val]
  942. vals = val.split(':')
  943. if len(vals) == 3:
  944. return tuple(float(v) / 255 for v in vals)
  945. return dflt
  946. # check GRASS_OVERWRITE
  947. def overwrite():
  948. """Return True if existing files may be overwritten"""
  949. owstr = 'GRASS_OVERWRITE'
  950. return owstr in os.environ and os.environ[owstr] != '0'
  951. # check GRASS_VERBOSE
  952. def verbosity():
  953. """Return the verbosity level selected by GRASS_VERBOSE"""
  954. vbstr = os.getenv('GRASS_VERBOSE')
  955. if vbstr:
  956. return int(vbstr)
  957. else:
  958. return 2
  959. ## various utilities, not specific to GRASS
  960. def find_program(pgm, *args):
  961. """Attempt to run a program, with optional arguments.
  962. You must call the program in a way that will return a successful
  963. exit code. For GRASS modules this means you need to pass it some
  964. valid CLI option, like "--help". For other programs a common
  965. valid do-little option is usually "--version".
  966. Example:
  967. >>> find_program('r.sun', '--help')
  968. True
  969. >>> find_program('ls', '--version')
  970. True
  971. :param str pgm: program name
  972. :param args: list of arguments
  973. :return: False if the attempt failed due to a missing executable
  974. or non-zero return code
  975. :return: True otherwise
  976. """
  977. nuldev = file(os.devnull, 'w+')
  978. try:
  979. # TODO: the doc or impl is not correct, any return code is accepted
  980. call([pgm] + list(args), stdin = nuldev, stdout = nuldev, stderr = nuldev)
  981. found = True
  982. except:
  983. found = False
  984. nuldev.close()
  985. return found
  986. # interface to g.mapsets
  987. def mapsets(search_path=False):
  988. """List available mapsets
  989. :param bool search_path: True to list mapsets only in search path
  990. :return: list of mapsets
  991. """
  992. if search_path:
  993. flags = 'p'
  994. else:
  995. flags = 'l'
  996. mapsets = read_command('g.mapsets',
  997. flags=flags,
  998. sep='newline',
  999. quiet=True)
  1000. if not mapsets:
  1001. fatal(_("Unable to list mapsets"))
  1002. return mapsets.splitlines()
  1003. # interface to `g.proj -c`
  1004. def create_location(dbase, location, epsg=None, proj4=None, filename=None,
  1005. wkt=None, datum=None, datum_trans=None, desc=None,
  1006. overwrite=False):
  1007. """Create new location
  1008. Raise ScriptError on error.
  1009. :param str dbase: path to GRASS database
  1010. :param str location: location name to create
  1011. :param epsg: if given create new location based on EPSG code
  1012. :param proj4: if given create new location based on Proj4 definition
  1013. :param str filename: if given create new location based on georeferenced file
  1014. :param str wkt: if given create new location based on WKT definition
  1015. (path to PRJ file)
  1016. :param datum: GRASS format datum code
  1017. :param datum_trans: datum transformation parameters (used for epsg and proj4)
  1018. :param desc: description of the location (creates MYNAME file)
  1019. :param bool overwrite: True to overwrite location if exists(WARNING:
  1020. ALL DATA from existing location ARE DELETED!)
  1021. """
  1022. gisdbase = None
  1023. if epsg or proj4 or filename or wkt:
  1024. # FIXME: changing GISDBASE mid-session is not background-job safe
  1025. gisdbase = gisenv()['GISDBASE']
  1026. run_command('g.gisenv', set='GISDBASE=%s' % dbase)
  1027. # create dbase if not exists
  1028. if not os.path.exists(dbase):
  1029. os.mkdir(dbase)
  1030. # check if location already exists
  1031. if os.path.exists(os.path.join(dbase, location)):
  1032. if not overwrite:
  1033. warning(_("Location <%s> already exists. Operation canceled.") % location)
  1034. return
  1035. else:
  1036. warning(_("Location <%s> already exists and will be overwritten") % location)
  1037. shutil.rmtree(os.path.join(dbase, location))
  1038. kwargs = dict()
  1039. if datum:
  1040. kwargs['datum'] = datum
  1041. if datum_trans:
  1042. kwargs['datum_trans'] = datum_trans
  1043. if epsg:
  1044. ps = pipe_command('g.proj', quiet=True, flags='t', epsg=epsg,
  1045. location=location, stderr=PIPE, **kwargs)
  1046. elif proj4:
  1047. ps = pipe_command('g.proj', quiet=True, flags='t', proj4=proj4,
  1048. location=location, stderr=PIPE, **kwargs)
  1049. elif filename:
  1050. ps = pipe_command('g.proj', quiet=True, georef=filename,
  1051. location=location, stderr=PIPE)
  1052. elif wkt:
  1053. ps = pipe_command('g.proj', quiet=True, wkt=wkt, location=location,
  1054. stderr=PIPE)
  1055. else:
  1056. _create_location_xy(dbase, location)
  1057. if epsg or proj4 or filename or wkt:
  1058. error = ps.communicate()[1]
  1059. run_command('g.gisenv', set='GISDBASE=%s' % gisdbase)
  1060. if ps.returncode != 0 and error:
  1061. raise ScriptError(repr(error))
  1062. try:
  1063. fd = codecs.open(os.path.join(dbase, location, 'PERMANENT', 'MYNAME'),
  1064. encoding='utf-8', mode='w')
  1065. if desc:
  1066. fd.write(desc + os.linesep)
  1067. else:
  1068. fd.write(os.linesep)
  1069. fd.close()
  1070. except OSError as e:
  1071. raise ScriptError(repr(e))
  1072. def _create_location_xy(database, location):
  1073. """Create unprojected location
  1074. Raise ScriptError on error.
  1075. :param database: GRASS database where to create new location
  1076. :param location: location name
  1077. """
  1078. cur_dir = os.getcwd()
  1079. try:
  1080. os.chdir(database)
  1081. os.mkdir(location)
  1082. os.mkdir(os.path.join(location, 'PERMANENT'))
  1083. # create DEFAULT_WIND and WIND files
  1084. regioninfo = ['proj: 0',
  1085. 'zone: 0',
  1086. 'north: 1',
  1087. 'south: 0',
  1088. 'east: 1',
  1089. 'west: 0',
  1090. 'cols: 1',
  1091. 'rows: 1',
  1092. 'e-w resol: 1',
  1093. 'n-s resol: 1',
  1094. 'top: 1',
  1095. 'bottom: 0',
  1096. 'cols3: 1',
  1097. 'rows3: 1',
  1098. 'depths: 1',
  1099. 'e-w resol3: 1',
  1100. 'n-s resol3: 1',
  1101. 't-b resol: 1']
  1102. defwind = open(os.path.join(location,
  1103. "PERMANENT", "DEFAULT_WIND"), 'w')
  1104. for param in regioninfo:
  1105. defwind.write(param + '%s' % os.linesep)
  1106. defwind.close()
  1107. shutil.copy(os.path.join(location, "PERMANENT", "DEFAULT_WIND"),
  1108. os.path.join(location, "PERMANENT", "WIND"))
  1109. os.chdir(cur_dir)
  1110. except OSError as e:
  1111. raise ScriptError(repr(e))
  1112. # interface to g.version
  1113. def version():
  1114. """Get GRASS version as dictionary
  1115. ::
  1116. print version()
  1117. {'proj4': '4.8.0', 'geos': '3.3.5', 'libgis_revision': '52468',
  1118. 'libgis_date': '2012-07-27 22:53:30 +0200 (Fri, 27 Jul 2012)',
  1119. 'version': '7.0.svn', 'date': '2012', 'gdal': '2.0dev',
  1120. 'revision': '53670'}
  1121. """
  1122. data = parse_command('g.version', flags='rge')
  1123. for k, v in data.iteritems():
  1124. data[k.strip()] = v.replace('"', '').strip()
  1125. return data
  1126. # get debug_level
  1127. _debug_level = None
  1128. def debug_level():
  1129. global _debug_level
  1130. if _debug_level is not None:
  1131. return _debug_level
  1132. _debug_level = 0
  1133. if find_program('g.gisenv', '--help'):
  1134. _debug_level = int(gisenv().get('DEBUG', 0))
  1135. return _debug_level
  1136. def legal_name(s):
  1137. """Checks if the string contains only allowed characters.
  1138. This is the Python implementation of G_legal_filename() function.
  1139. ..note::
  1140. It is not clear when to use this function.
  1141. """
  1142. if not s or s[0] == '.':
  1143. warning(_("Illegal filename <%s>. Cannot be 'NULL' or start with " \
  1144. "'.'.") % s)
  1145. return False
  1146. illegal = [c
  1147. for c in s
  1148. if c in '/"\'@,=*~' or c <= ' ' or c >= '\177']
  1149. if illegal:
  1150. illegal = ''.join(sorted(set(illegal)))
  1151. warning(_("Illegal filename <%(s)s>. <%(il)s> not allowed.\n") % {
  1152. 's': s, 'il': illegal})
  1153. return False
  1154. return True
  1155. if __name__ == '__main__':
  1156. import doctest
  1157. doctest.testmod()