core.py 48 KB

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