core.py 45 KB

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