core.py 47 KB

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