core.py 49 KB

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