core.py 46 KB

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