core.py 44 KB

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