core.py 45 KB

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