core.py 47 KB

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