core.py 47 KB

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