core.py 46 KB

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