core.py 51 KB

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