core.py 48 KB

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