core.py 46 KB

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