core.py 49 KB

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