core.py 50 KB

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