core.py 51 KB

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