core.py 50 KB

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