core.py 49 KB

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