core.py 44 KB

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