core.py 47 KB

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