core.py 47 KB

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