core.py 50 KB

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