core.py 49 KB

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