core.py 47 KB

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