core.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711
  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. if debug_level() >= debug:
  400. if sys.platform == "win32":
  401. msg = msg.replace('&', '^&')
  402. run_command("g.message", flags='d', message=msg, debug=debug)
  403. def verbose(msg):
  404. """!Display a verbose message using `g.message -v`
  405. @param msg verbose message to be displayed
  406. """
  407. message(msg, flag='v')
  408. def info(msg):
  409. """!Display an informational message using `g.message -i`
  410. @param msg informational message to be displayed
  411. """
  412. message(msg, flag='i')
  413. def percent(i, n, s):
  414. """!Display a progress info message using `g.message -p`
  415. @code
  416. message(_("Percent complete..."))
  417. n = 100
  418. for i in range(n):
  419. percent(i, n, 1)
  420. percent(1, 1, 1)
  421. @endcode
  422. @param i current item
  423. @param n total number of items
  424. @param s increment size
  425. """
  426. message("%d %d %d" % (i, n, s), flag='p')
  427. def warning(msg):
  428. """!Display a warning message using `g.message -w`
  429. @param msg warning message to be displayed
  430. """
  431. message(msg, flag='w')
  432. def error(msg):
  433. """!Display an error message using `g.message -e`
  434. @param msg error message to be displayed
  435. """
  436. message(msg, flag='e')
  437. def fatal(msg):
  438. """!Display an error message using `g.message -e`, then abort
  439. Raise exception when raise_on_error is 'True'.
  440. @param msg error message to be displayed
  441. """
  442. global raise_on_error
  443. if raise_on_error:
  444. raise ScriptError(msg)
  445. error(msg)
  446. sys.exit(1)
  447. def set_raise_on_error(raise_exp=True):
  448. """!Define behaviour on fatal error (fatal() called)
  449. @param raise_exp True to raise ScriptError instead of calling
  450. sys.exit(1) in fatal()
  451. @return current status
  452. """
  453. global raise_on_error
  454. tmp_raise = raise_on_error
  455. raise_on_error = raise_exp
  456. return tmp_raise
  457. def get_raise_on_error():
  458. """!Return True if a ScriptError exception is raised instead of calling
  459. sys.exit(1) in case a fatal error was invoked with fatal()
  460. """
  461. global raise_on_error
  462. return raise_on_error
  463. # interface to g.parser
  464. def _parse_opts(lines):
  465. options = {}
  466. flags = {}
  467. for line in lines:
  468. if not line:
  469. break
  470. try:
  471. [var, val] = line.split('=', 1)
  472. except:
  473. raise SyntaxError("invalid output from g.parser: %s" % line)
  474. if var.startswith('flag_'):
  475. flags[var[5:]] = bool(int(val))
  476. elif var.startswith('opt_'):
  477. options[var[4:]] = val
  478. elif var in ['GRASS_OVERWRITE', 'GRASS_VERBOSE']:
  479. os.environ[var] = val
  480. else:
  481. raise SyntaxError("invalid output from g.parser: %s" % line)
  482. return (options, flags)
  483. def parser():
  484. """!Interface to g.parser, intended to be run from the top-level, e.g.:
  485. @code
  486. if __name__ == "__main__":
  487. options, flags = grass.parser()
  488. main()
  489. @endcode
  490. Thereafter, the global variables "options" and "flags" will be
  491. dictionaries containing option/flag values, keyed by lower-case
  492. option/flag names. The values in "options" are strings, those in
  493. "flags" are Python booleans.
  494. """
  495. if not os.getenv("GISBASE"):
  496. print >> sys.stderr, "You must be in GRASS GIS to run this program."
  497. sys.exit(1)
  498. cmdline = [basename(sys.argv[0])]
  499. cmdline += ['"' + arg + '"' for arg in sys.argv[1:]]
  500. os.environ['CMDLINE'] = ' '.join(cmdline)
  501. argv = sys.argv[:]
  502. name = argv[0]
  503. if not os.path.isabs(name):
  504. if os.sep in name or (os.altsep and os.altsep in name):
  505. argv[0] = os.path.abspath(name)
  506. else:
  507. argv[0] = os.path.join(sys.path[0], name)
  508. p = Popen(['g.parser', '-n'] + argv, stdout=PIPE)
  509. s = p.communicate()[0]
  510. lines = s.split('\0')
  511. if not lines or lines[0] != "@ARGS_PARSED@":
  512. sys.stdout.write(s)
  513. sys.exit(p.returncode)
  514. return _parse_opts(lines[1:])
  515. # interface to g.tempfile
  516. def tempfile(create=True):
  517. """!Returns the name of a temporary file, created with
  518. g.tempfile.
  519. @param create True to create a file
  520. @return path to a tmp file
  521. """
  522. flags = ''
  523. if not create:
  524. flags += 'd'
  525. return read_command("g.tempfile", flags=flags, pid=os.getpid()).strip()
  526. def tempdir():
  527. """!Returns the name of a temporary dir, created with g.tempfile."""
  528. tmp = tempfile(create=False)
  529. os.mkdir(tmp)
  530. return tmp
  531. class KeyValue(dict):
  532. """A general-purpose key-value store.
  533. KeyValue is a subclass of dict, but also allows entries to be read and
  534. written using attribute syntax. Example:
  535. \code
  536. >>> reg = KeyValue()
  537. >>> reg['north'] = 489
  538. >>> reg.north
  539. 489
  540. >>> reg.south = 205
  541. >>> reg['south']
  542. 205
  543. \endcode
  544. """
  545. def __getattr__(self, key):
  546. return self[key]
  547. def __setattr__(self, key, value):
  548. self[key] = value
  549. # key-value parsers
  550. def parse_key_val(s, sep='=', dflt=None, val_type=None, vsep=None):
  551. """!Parse a string into a dictionary, where entries are separated
  552. by newlines and the key and value are separated by `sep' (default: `=')
  553. @param s string to be parsed
  554. @param sep key/value separator
  555. @param dflt default value to be used
  556. @param val_type value type (None for no cast)
  557. @param vsep vertical separator (default os.linesep)
  558. @return parsed input (dictionary of keys/values)
  559. """
  560. result = KeyValue()
  561. if not s:
  562. return result
  563. if vsep:
  564. lines = s.split(vsep)
  565. try:
  566. lines.remove('\n')
  567. except ValueError:
  568. pass
  569. else:
  570. lines = s.splitlines()
  571. for line in lines:
  572. kv = line.split(sep, 1)
  573. k = kv[0].strip()
  574. if len(kv) > 1:
  575. v = kv[1].strip()
  576. else:
  577. v = dflt
  578. if val_type:
  579. result[k] = val_type(v)
  580. else:
  581. result[k] = v
  582. return result
  583. def _compare_projection(dic):
  584. """
  585. !Check if projection has some possibility of duplicate names like
  586. Universal Transverse Mercator and Universe Transverse Mercator and
  587. unify them
  588. @param dic The dictionary containing information about projection
  589. @return The dictionary with the new values if needed
  590. """
  591. # the lookup variable is a list of list, each list contains all the
  592. # possible name for a projection system
  593. lookup = [['Universal Transverse Mercator', 'Universe Transverse Mercator']]
  594. for lo in lookup:
  595. for n in range(len(dic['name'])):
  596. if dic['name'][n] in lo:
  597. dic['name'][n] = lo[0]
  598. return dic
  599. def _compare_units(dic):
  600. """
  601. !Check if units has some possibility of duplicate names like
  602. meter and metre and unify them
  603. @param dic The dictionary containing information about units
  604. @return The dictionary with the new values if needed
  605. """
  606. # the lookup variable is a list of list, each list contains all the
  607. # possible name for a units
  608. lookup = [['meter', 'metre'], ['meters', 'metres'], ['kilometer',
  609. 'kilometre'], ['kilometers', 'kilometres']]
  610. for l in lookup:
  611. for n in range(len(dic['unit'])):
  612. if dic['unit'][n] in l:
  613. dic['unit'][n] = l[0]
  614. for n in range(len(dic['units'])):
  615. if dic['units'][n] in l:
  616. dic['units'][n] = l[0]
  617. return dic
  618. def _text_to_key_value_dict(filename, sep=":", val_sep=",", checkproj=False,
  619. checkunits=False):
  620. """
  621. !Convert a key-value text file, where entries are separated
  622. by newlines and the key and value are separated by `sep',
  623. into a key-value dictionary and discover/use the correct
  624. data types (float, int or string) for values.
  625. @param filename The name or name and path of the text file to convert
  626. @param sep The character that separates the keys and values, default is ":"
  627. @param val_sep The character that separates the values of a single key, default is ","
  628. @param checkproj True if it has to check some information about projection system
  629. @param checkproj True if it has to check some information about units
  630. @return The dictionary
  631. A text file with this content:
  632. \code
  633. a: Hello
  634. b: 1.0
  635. c: 1,2,3,4,5
  636. d : hello,8,0.1
  637. \endcode
  638. Will be represented as this dictionary:
  639. \code
  640. {'a': ['Hello'], 'c': [1, 2, 3, 4, 5], 'b': [1.0], 'd': ['hello', 8, 0.1]}
  641. \endcode
  642. """
  643. text = open(filename, "r").readlines()
  644. kvdict = KeyValue()
  645. for line in text:
  646. if line.find(sep) >= 0:
  647. key, value = line.split(sep)
  648. key = key.strip()
  649. value = value.strip()
  650. else:
  651. # Jump over empty values
  652. continue
  653. values = value.split(val_sep)
  654. value_list = []
  655. for value in values:
  656. not_float = False
  657. not_int = False
  658. # Convert values into correct types
  659. # We first try integer then float
  660. try:
  661. value_converted = int(value)
  662. except:
  663. not_int = True
  664. if not_int:
  665. try:
  666. value_converted = float(value)
  667. except:
  668. not_float = True
  669. if not_int and not_float:
  670. value_converted = value.strip()
  671. value_list.append(value_converted)
  672. kvdict[key] = value_list
  673. if checkproj:
  674. kvdict = _compare_projection(kvdict)
  675. if checkunits:
  676. kvdict = _compare_units(kvdict)
  677. return kvdict
  678. def compare_key_value_text_files(filename_a, filename_b, sep=":",
  679. val_sep=",", precision=0.000001,
  680. proj=False, units=False):
  681. """
  682. !Compare two key-value text files
  683. This method will print a warning in case keys that are present in the first
  684. file are not present in the second one.
  685. The comparison method tries to convert the values into their native format
  686. (float, int or string) to allow correct comparison.
  687. An example key-value text file may have this content:
  688. \code
  689. a: Hello
  690. b: 1.0
  691. c: 1,2,3,4,5
  692. d : hello,8,0.1
  693. \endcode
  694. @param filename_a name of the first key-value text file
  695. @param filenmae_b name of the second key-value text file
  696. @param sep character that separates the keys and values, default is ":"
  697. @param val_sep character that separates the values of a single key, default is ","
  698. @param precision precision with which the floating point values are compared
  699. @param proj True if it has to check some information about projection system
  700. @param units True if it has to check some information about units
  701. @return True if full or almost identical, False if different
  702. """
  703. dict_a = _text_to_key_value_dict(filename_a, sep, checkproj=proj,
  704. checkunits=units)
  705. dict_b = _text_to_key_value_dict(filename_b, sep, checkproj=proj,
  706. checkunits=units)
  707. if sorted(dict_a.keys()) != sorted(dict_b.keys()):
  708. return False
  709. # We compare matching keys
  710. for key in dict_a.keys():
  711. # Floating point values must be handled separately
  712. if isinstance(dict_a[key], float) and isinstance(dict_b[key], float):
  713. if abs(dict_a[key] - dict_b[key]) > precision:
  714. return False
  715. elif isinstance(dict_a[key], float) or isinstance(dict_b[key], float):
  716. warning(_("Mixing value types. Will try to compare after "
  717. "integer conversion"))
  718. return int(dict_a[key]) == int(dict_b[key])
  719. elif key == "+towgs84":
  720. # We compare the sum of the entries
  721. if abs(sum(dict_a[key]) - sum(dict_b[key])) > precision:
  722. return False
  723. else:
  724. if dict_a[key] != dict_b[key]:
  725. return False
  726. return True
  727. def diff_files(filename_a, filename_b):
  728. """!Diffs two text files and returns difference.
  729. @param filename_a first file path
  730. @param filename_b second file path
  731. @return list of strings
  732. """
  733. import difflib
  734. differ = difflib.Differ()
  735. fh_a = open(filename_a, 'r')
  736. fh_b = open(filename_b, 'r')
  737. result = list(differ.compare(fh_a.readlines(),
  738. fh_b.readlines()))
  739. return result
  740. # interface to g.gisenv
  741. def gisenv():
  742. """!Returns the output from running g.gisenv (with no arguments), as a
  743. dictionary. Example:
  744. @code
  745. >>> env = gisenv()
  746. >>> print env['GISDBASE'] # doctest: +SKIP
  747. /opt/grass-data
  748. @endcode
  749. @return list of GRASS variables
  750. """
  751. s = read_command("g.gisenv", flags='n')
  752. return parse_key_val(s)
  753. # interface to g.region
  754. def locn_is_latlong():
  755. """!Tests if location is lat/long. Value is obtained
  756. by checking the "g.region -pu" projection code.
  757. @return True for a lat/long region, False otherwise
  758. """
  759. s = read_command("g.region", flags='pu')
  760. kv = parse_key_val(s, ':')
  761. if kv['projection'].split(' ')[0] == '3':
  762. return True
  763. else:
  764. return False
  765. def region(region3d=False, complete=False):
  766. """!Returns the output from running "g.region -gu", as a
  767. dictionary. Example:
  768. @param region3d True to get 3D region
  769. @code
  770. >>> curent_region = region()
  771. >>> # obtain n, s, e and w values
  772. >>> [curent_region[key] for key in "nsew"] # doctest: +ELLIPSIS
  773. [..., ..., ..., ...]
  774. >>> # obtain ns and ew resulutions
  775. >>> (curent_region['nsres'], curent_region['ewres']) # doctest: +ELLIPSIS
  776. (..., ...)
  777. @endcode
  778. @return dictionary of region values
  779. """
  780. flgs = 'gu'
  781. if region3d:
  782. flgs += '3'
  783. if complete:
  784. flgs += 'cep'
  785. s = read_command("g.region", flags=flgs)
  786. reg = parse_key_val(s, val_type=float)
  787. for k in ['rows', 'cols', 'cells',
  788. 'rows3', 'cols3', 'cells3', 'depths']:
  789. if k not in reg:
  790. continue
  791. reg[k] = int(reg[k])
  792. return reg
  793. def region_env(region3d=False, **kwargs):
  794. """!Returns region settings as a string which can used as
  795. GRASS_REGION environmental variable.
  796. If no 'kwargs' are given then the current region is used. Note
  797. that this function doesn't modify the current region!
  798. See also use_temp_region() for alternative method how to define
  799. temporary region used for raster-based computation.
  800. \param region3d True to get 3D region
  801. \param kwargs g.region's parameters like 'rast', 'vect' or 'region'
  802. \code
  803. os.environ['GRASS_REGION'] = grass.region_env(region='detail')
  804. grass.mapcalc('map=1', overwrite=True)
  805. os.environ.pop('GRASS_REGION')
  806. \endcode
  807. @return string with region values
  808. @return empty string on error
  809. """
  810. # read proj/zone from WIND file
  811. env = gisenv()
  812. windfile = os.path.join(env['GISDBASE'], env['LOCATION_NAME'],
  813. env['MAPSET'], "WIND")
  814. fd = open(windfile, "r")
  815. grass_region = ''
  816. for line in fd.readlines():
  817. key, value = map(lambda x: x.strip(), line.split(":", 1))
  818. if kwargs and key not in ('proj', 'zone'):
  819. continue
  820. if not kwargs and not region3d and \
  821. key in ('top', 'bottom', 'cols3', 'rows3',
  822. 'depths', 'e-w resol3', 'n-s resol3', 't-b resol'):
  823. continue
  824. grass_region += '%s: %s;' % (key, value)
  825. if not kwargs: # return current region
  826. return grass_region
  827. # read other values from `g.region -gu`
  828. flgs = 'ug'
  829. if region3d:
  830. flgs += '3'
  831. s = read_command('g.region', flags=flgs, **kwargs)
  832. if not s:
  833. return ''
  834. reg = parse_key_val(s)
  835. kwdata = [('north', 'n'),
  836. ('south', 's'),
  837. ('east', 'e'),
  838. ('west', 'w'),
  839. ('cols', 'cols'),
  840. ('rows', 'rows'),
  841. ('e-w resol', 'ewres'),
  842. ('n-s resol', 'nsres')]
  843. if region3d:
  844. kwdata += [('top', 't'),
  845. ('bottom', 'b'),
  846. ('cols3', 'cols3'),
  847. ('rows3', 'rows3'),
  848. ('depths', 'depths'),
  849. ('e-w resol3', 'ewres3'),
  850. ('n-s resol3', 'nsres3'),
  851. ('t-b resol', 'tbres')]
  852. for wkey, rkey in kwdata:
  853. grass_region += '%s: %s;' % (wkey, reg[rkey])
  854. return grass_region
  855. def use_temp_region():
  856. """!Copies the current region to a temporary region with "g.region save=",
  857. then sets WIND_OVERRIDE to refer to that region. Installs an atexit
  858. handler to delete the temporary region upon termination.
  859. """
  860. name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
  861. run_command("g.region", save=name, overwrite=True)
  862. os.environ['WIND_OVERRIDE'] = name
  863. atexit.register(del_temp_region)
  864. def del_temp_region():
  865. """!Unsets WIND_OVERRIDE and removes any region named by it."""
  866. try:
  867. name = os.environ.pop('WIND_OVERRIDE')
  868. run_command("g.remove", quiet=True, region=name)
  869. except:
  870. pass
  871. # interface to g.findfile
  872. def find_file(name, element='cell', mapset=None):
  873. """!Returns the output from running g.findfile as a
  874. dictionary. Example:
  875. @code
  876. >>> result = find_file('elevation', element='cell')
  877. >>> print result['fullname']
  878. elevation@PERMANENT
  879. >>> print result['file'] # doctest: +ELLIPSIS
  880. /.../PERMANENT/cell/elevation
  881. @endcode
  882. @param name file name
  883. @param element element type (default 'cell')
  884. @param mapset mapset name (default all mapsets in search path)
  885. @return parsed output of g.findfile
  886. """
  887. if element == 'raster' or element == 'rast':
  888. verbose(_('Element type should be "cell" and not "%s"') % element)
  889. element = 'cell'
  890. s = read_command("g.findfile", flags='n', element=element, file=name,
  891. mapset=mapset)
  892. return parse_key_val(s)
  893. # interface to g.list
  894. def list_grouped(type, check_search_path=True):
  895. """!List elements grouped by mapsets.
  896. Returns the output from running g.list, as a dictionary where the
  897. keys are mapset names and the values are lists of maps in that
  898. mapset. Example:
  899. @code
  900. >>> list_grouped('rast')['PERMANENT'] # doctest: +ELLIPSIS
  901. [..., 'lakes', ..., 'slope', ...
  902. @endcode
  903. @param type element type (rast, vect, rast3d, region, ...)
  904. @param check_search_path True to add mapsets for the search path with no
  905. found elements
  906. @return directory of mapsets/elements
  907. """
  908. if type == 'raster' or type == 'cell':
  909. verbose(_('Element type should be "rast" and not "%s"') % type)
  910. type = 'rast'
  911. dashes_re = re.compile("^----+$")
  912. mapset_re = re.compile("<(.*)>")
  913. result = {}
  914. if check_search_path:
  915. for mapset in mapsets(search_path=True):
  916. result[mapset] = []
  917. mapset = None
  918. for line in read_command("g.list", type=type).splitlines():
  919. if line == "":
  920. continue
  921. if dashes_re.match(line):
  922. continue
  923. m = mapset_re.search(line)
  924. if m:
  925. mapset = m.group(1)
  926. if mapset not in result.keys():
  927. result[mapset] = []
  928. continue
  929. if mapset:
  930. result[mapset].extend(line.split())
  931. return result
  932. def _concat(xs):
  933. result = []
  934. for x in xs:
  935. result.extend(x)
  936. return result
  937. def list_pairs(type):
  938. """!List of elements as tuples.
  939. Returns the output from running g.list, as a list of (map, mapset)
  940. pairs. Example:
  941. @code
  942. >>> list_pairs('rast') # doctest: +ELLIPSIS
  943. [..., ('lakes', 'PERMANENT'), ..., ('slope', 'PERMANENT'), ...
  944. @endcode
  945. @param type element type (rast, vect, rast3d, region, ...)
  946. @return list of tuples (map, mapset)
  947. """
  948. return _concat([[(map, mapset) for map in maps]
  949. for mapset, maps in list_grouped(type).iteritems()])
  950. def list_strings(type):
  951. """!List of elements as strings.
  952. Returns the output from running g.list, as a list of qualified
  953. names. Example:
  954. @code
  955. >>> list_strings('rast') # doctest: +ELLIPSIS
  956. [..., 'lakes@PERMANENT', ..., 'slope@PERMANENT', ...
  957. @endcode
  958. @param type element type
  959. @return list of strings ('map@@mapset')
  960. """
  961. return ["%s@%s" % pair for pair in list_pairs(type)]
  962. # interface to g.mlist
  963. def mlist_strings(type, pattern=None, mapset=None, flag=''):
  964. """!List of elements as strings.
  965. Returns the output from running g.mlist, as a list of qualified
  966. names.
  967. @param type element type (rast, vect, rast3d, region, ...)
  968. @param pattern pattern string
  969. @param mapset mapset name (if not given use search path)
  970. @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or ''
  971. (glob pattern)
  972. @return list of elements
  973. """
  974. if type == 'raster' or type == 'cell':
  975. verbose(_('Element type should be "rast" and not "%s"') % type)
  976. type = 'rast'
  977. result = list()
  978. for line in read_command("g.mlist",
  979. quiet=True,
  980. flags='m' + flag,
  981. type=type,
  982. pattern=pattern,
  983. mapset=mapset).splitlines():
  984. result.append(line.strip())
  985. return result
  986. def mlist_pairs(type, pattern=None, mapset=None, flag=''):
  987. """!List of elements as pairs
  988. Returns the output from running g.mlist, as a list of
  989. (name, mapset) pairs
  990. @param type element type (rast, vect, rast3d, region, ...)
  991. @param pattern pattern string
  992. @param mapset mapset name (if not given use search path)
  993. @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or ''
  994. (glob pattern)
  995. @return list of elements
  996. """
  997. return [tuple(map.split('@', 1)) for map in mlist_strings(type, pattern,
  998. mapset, flag)]
  999. def mlist_grouped(type, pattern=None, check_search_path=True, flag=''):
  1000. """!List of elements grouped by mapsets.
  1001. Returns the output from running g.mlist, as a dictionary where the
  1002. keys are mapset names and the values are lists of maps in that
  1003. mapset. Example:
  1004. @code
  1005. >>> mlist_grouped('vect', pattern='*roads*')['PERMANENT']
  1006. ['railroads', 'roadsmajor']
  1007. @endcode
  1008. @param type element type (rast, vect, rast3d, region, ...)
  1009. @param pattern pattern string
  1010. @param check_search_path True to add mapsets for the search path with no
  1011. found elements
  1012. @param flag pattern type: 'r' (basic regexp), 'e' (extended regexp), or ''
  1013. (glob pattern)
  1014. @return directory of mapsets/elements
  1015. """
  1016. if type == 'raster' or type == 'cell':
  1017. verbose(_('Element type should be "rast" and not "%s"') % type)
  1018. type = 'rast'
  1019. result = {}
  1020. if check_search_path:
  1021. for mapset in mapsets(search_path=True):
  1022. result[mapset] = []
  1023. mapset = None
  1024. for line in read_command("g.mlist", quiet=True, flags="m" + flag,
  1025. type=type, pattern=pattern).splitlines():
  1026. try:
  1027. name, mapset = line.split('@')
  1028. except ValueError:
  1029. warning(_("Invalid element '%s'") % line)
  1030. continue
  1031. if mapset in result:
  1032. result[mapset].append(name)
  1033. else:
  1034. result[mapset] = [name, ]
  1035. return result
  1036. # color parsing
  1037. named_colors = {
  1038. "white": (1.00, 1.00, 1.00),
  1039. "black": (0.00, 0.00, 0.00),
  1040. "red": (1.00, 0.00, 0.00),
  1041. "green": (0.00, 1.00, 0.00),
  1042. "blue": (0.00, 0.00, 1.00),
  1043. "yellow": (1.00, 1.00, 0.00),
  1044. "magenta": (1.00, 0.00, 1.00),
  1045. "cyan": (0.00, 1.00, 1.00),
  1046. "aqua": (0.00, 0.75, 0.75),
  1047. "grey": (0.75, 0.75, 0.75),
  1048. "gray": (0.75, 0.75, 0.75),
  1049. "orange": (1.00, 0.50, 0.00),
  1050. "brown": (0.75, 0.50, 0.25),
  1051. "purple": (0.50, 0.00, 1.00),
  1052. "violet": (0.50, 0.00, 1.00),
  1053. "indigo": (0.00, 0.50, 1.00)}
  1054. def parse_color(val, dflt=None):
  1055. """!Parses the string "val" as a GRASS colour, which can be either one of
  1056. the named colours or an R:G:B tuple e.g. 255:255:255. Returns an
  1057. (r,g,b) triple whose components are floating point values between 0
  1058. and 1. Example:
  1059. @code
  1060. >>> parse_color("red")
  1061. (1.0, 0.0, 0.0)
  1062. >>> parse_color("255:0:0")
  1063. (1.0, 0.0, 0.0)
  1064. @endcode
  1065. @param val color value
  1066. @param dflt default color value
  1067. @return tuple RGB
  1068. """
  1069. if val in named_colors:
  1070. return named_colors[val]
  1071. vals = val.split(':')
  1072. if len(vals) == 3:
  1073. return tuple(float(v) / 255 for v in vals)
  1074. return dflt
  1075. # check GRASS_OVERWRITE
  1076. def overwrite():
  1077. """!Return True if existing files may be overwritten"""
  1078. owstr = 'GRASS_OVERWRITE'
  1079. return owstr in os.environ and os.environ[owstr] != '0'
  1080. # check GRASS_VERBOSE
  1081. def verbosity():
  1082. """!Return the verbosity level selected by GRASS_VERBOSE"""
  1083. vbstr = os.getenv('GRASS_VERBOSE')
  1084. if vbstr:
  1085. return int(vbstr)
  1086. else:
  1087. return 2
  1088. ## various utilities, not specific to GRASS
  1089. # basename inc. extension stripping
  1090. def basename(path, ext=None):
  1091. """!Remove leading directory components and an optional extension
  1092. from the specified path
  1093. @param path path
  1094. @param ext extension
  1095. """
  1096. name = os.path.basename(path)
  1097. if not ext:
  1098. return name
  1099. fs = name.rsplit('.', 1)
  1100. if len(fs) > 1 and fs[1].lower() == ext:
  1101. name = fs[0]
  1102. return name
  1103. def find_program(pgm, *args):
  1104. """!Attempt to run a program, with optional arguments.
  1105. You must call the program in a way that will return a successful
  1106. exit code. For GRASS modules this means you need to pass it some
  1107. valid CLI option, like "--help". For other programs a common
  1108. valid do-little option is "--version".
  1109. Example:
  1110. @code
  1111. >>> grass.find_program('r.sun', 'help')
  1112. True
  1113. >>> grass.find_program('gdalwarp', '--version')
  1114. True
  1115. @endcode
  1116. @param pgm program name
  1117. @param args list of arguments
  1118. @return False if the attempt failed due to a missing executable
  1119. or non-zero return code
  1120. @return True otherwise
  1121. """
  1122. nuldev = file(os.devnull, 'w+')
  1123. try:
  1124. call([pgm] + list(args), stdin = nuldev, stdout = nuldev, stderr = nuldev)
  1125. found = True
  1126. except:
  1127. found = False
  1128. nuldev.close()
  1129. return found
  1130. # try to remove a file, without complaints
  1131. def try_remove(path):
  1132. """!Attempt to remove a file; no exception is generated if the
  1133. attempt fails.
  1134. @param path path to file to remove
  1135. """
  1136. try:
  1137. os.remove(path)
  1138. except:
  1139. pass
  1140. # try to remove a directory, without complaints
  1141. def try_rmdir(path):
  1142. """!Attempt to remove a directory; no exception is generated if the
  1143. attempt fails.
  1144. @param path path to directory to remove
  1145. """
  1146. try:
  1147. os.rmdir(path)
  1148. except:
  1149. shutil.rmtree(path, ignore_errors=True)
  1150. def float_or_dms(s):
  1151. """!Convert DMS to float.
  1152. @param s DMS value
  1153. @return float value
  1154. """
  1155. return sum(float(x) / 60 ** n for (n, x) in enumerate(s.split(':')))
  1156. # interface to g.mapsets
  1157. def mapsets(search_path=False):
  1158. """!List available mapsets
  1159. @param search_path True to list mapsets only in search path
  1160. @return list of mapsets
  1161. """
  1162. if search_path:
  1163. flags = 'p'
  1164. else:
  1165. flags = 'l'
  1166. mapsets = read_command('g.mapsets',
  1167. flags=flags,
  1168. sep='newline',
  1169. quiet=True)
  1170. if not mapsets:
  1171. fatal(_("Unable to list mapsets"))
  1172. return mapsets.splitlines()
  1173. # interface to `g.proj -c`
  1174. def create_location(dbase, location, epsg=None, proj4=None, filename=None,
  1175. wkt=None, datum=None, datum_trans=None, desc=None, overwrite=False):
  1176. """!Create new location
  1177. Raise ScriptError on error.
  1178. @param dbase path to GRASS database
  1179. @param location location name to create
  1180. @param epsg if given create new location based on EPSG code
  1181. @param proj4 if given create new location based on Proj4 definition
  1182. @param filename if given create new location based on georeferenced file
  1183. @param wkt if given create new location based on WKT definition (path to PRJ file)
  1184. @param datum GRASS format datum code
  1185. @param datum_trans datum transformation parameters (used for epsg and proj4)
  1186. @param desc description of the location (creates MYNAME file)
  1187. @param overwrite True to overwrite location if exists (WARNING: ALL DATA from existing location ARE DELETED!)
  1188. """
  1189. gisdbase = None
  1190. if epsg or proj4 or filename or wkt:
  1191. # FIXME: changing GISDBASE mid-session is not background-job safe
  1192. gisdbase = gisenv()['GISDBASE']
  1193. run_command('g.gisenv', set='GISDBASE=%s' % dbase)
  1194. # create dbase if not exists
  1195. if not os.path.exists(dbase):
  1196. os.mkdir(dbase)
  1197. # check if location already exists
  1198. if os.path.exists(os.path.join(dbase, location)):
  1199. if not overwrite:
  1200. warning(_("Location <%s> already exists. Operation canceled.") % location)
  1201. return
  1202. else:
  1203. warning(_("Location <%s> already exists and will be overwritten") % location)
  1204. shutil.rmtree(os.path.join(dbase, location))
  1205. kwargs = dict()
  1206. if datum:
  1207. kwargs['datum'] = datum
  1208. if datum_trans:
  1209. kwargs['datum_trans'] = datum_trans
  1210. if epsg:
  1211. ps = pipe_command('g.proj', quiet=True, flags='t', epsg=epsg,
  1212. location=location, stderr=PIPE, **kwargs)
  1213. elif proj4:
  1214. ps = pipe_command('g.proj', quiet=True, flags='t', proj4=proj4,
  1215. location=location, stderr=PIPE, **kwargs)
  1216. elif filename:
  1217. ps = pipe_command('g.proj', quiet=True, georef=filename,
  1218. location=location, stderr=PIPE)
  1219. elif wkt:
  1220. ps = pipe_command('g.proj', quiet=True, wkt=wkt, location=location,
  1221. stderr=PIPE)
  1222. else:
  1223. _create_location_xy(dbase, location)
  1224. if epsg or proj4 or filename or wkt:
  1225. error = ps.communicate()[1]
  1226. run_command('g.gisenv', set='GISDBASE=%s' % gisdbase)
  1227. if ps.returncode != 0 and error:
  1228. raise ScriptError(repr(error))
  1229. try:
  1230. fd = codecs.open(os.path.join(dbase, location, 'PERMANENT', 'MYNAME'),
  1231. encoding='utf-8', mode='w')
  1232. if desc:
  1233. fd.write(desc + os.linesep)
  1234. else:
  1235. fd.write(os.linesep)
  1236. fd.close()
  1237. except OSError, e:
  1238. raise ScriptError(repr(e))
  1239. def _create_location_xy(database, location):
  1240. """!Create unprojected location
  1241. Raise ScriptError on error.
  1242. @param database GRASS database where to create new location
  1243. @param location location name
  1244. """
  1245. cur_dir = os.getcwd()
  1246. try:
  1247. os.chdir(database)
  1248. os.mkdir(location)
  1249. os.mkdir(os.path.join(location, 'PERMANENT'))
  1250. # create DEFAULT_WIND and WIND files
  1251. regioninfo = ['proj: 0',
  1252. 'zone: 0',
  1253. 'north: 1',
  1254. 'south: 0',
  1255. 'east: 1',
  1256. 'west: 0',
  1257. 'cols: 1',
  1258. 'rows: 1',
  1259. 'e-w resol: 1',
  1260. 'n-s resol: 1',
  1261. 'top: 1',
  1262. 'bottom: 0',
  1263. 'cols3: 1',
  1264. 'rows3: 1',
  1265. 'depths: 1',
  1266. 'e-w resol3: 1',
  1267. 'n-s resol3: 1',
  1268. 't-b resol: 1']
  1269. defwind = open(os.path.join(location,
  1270. "PERMANENT", "DEFAULT_WIND"), 'w')
  1271. for param in regioninfo:
  1272. defwind.write(param + '%s' % os.linesep)
  1273. defwind.close()
  1274. shutil.copy(os.path.join(location, "PERMANENT", "DEFAULT_WIND"),
  1275. os.path.join(location, "PERMANENT", "WIND"))
  1276. os.chdir(cur_dir)
  1277. except OSError, e:
  1278. raise ScriptError(repr(e))
  1279. # interface to g.version
  1280. def version():
  1281. """!Get GRASS version as dictionary
  1282. @code
  1283. print version()
  1284. {'proj4': '4.8.0', 'geos': '3.3.5', 'libgis_revision': '52468',
  1285. 'libgis_date': '2012-07-27 22:53:30 +0200 (Fri, 27 Jul 2012)',
  1286. 'version': '7.0.svn', 'date': '2012', 'gdal': '2.0dev',
  1287. 'revision': '53670'}
  1288. @endcode
  1289. """
  1290. data = parse_command('g.version', flags='rge')
  1291. for k, v in data.iteritems():
  1292. data[k.strip()] = v.replace('"', '').strip()
  1293. return data
  1294. # get debug_level
  1295. _debug_level = None
  1296. def debug_level():
  1297. global _debug_level
  1298. if _debug_level is not None:
  1299. return _debug_level
  1300. _debug_level = 0
  1301. if find_program('g.gisenv', '--help'):
  1302. _debug_level = int(gisenv().get('DEBUG', 0))
  1303. def legal_name(s):
  1304. """!Checks if the string contains only allowed characters.
  1305. This is the Python implementation of G_legal_filename() function.
  1306. @note It is not clear when to use this function.
  1307. """
  1308. if not s or s[0] == '.':
  1309. warning(_("Illegal filename <%s>. Cannot be 'NULL' or start with " \
  1310. "'.'.") % s)
  1311. return False
  1312. illegal = [c
  1313. for c in s
  1314. if c in '/"\'@,=*~' or c <= ' ' or c >= '\177']
  1315. if illegal:
  1316. illegal = ''.join(sorted(set(illegal)))
  1317. warning(_("Illegal filename <%(s)s>. <%(il)s> not allowed.\n") % {
  1318. 's': s, 'il': illegal})
  1319. return False
  1320. return True
  1321. if __name__ == '__main__':
  1322. import doctest
  1323. doctest.testmod()