core.py 47 KB

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