core.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510
  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 val != None:
  227. if opt.startswith('_'):
  228. opt = opt[1:]
  229. warning(_("To run the module add underscore at the end"
  230. " of the option <%s> to avoid conflict with Python"
  231. " keywords. Underscore at the beginning is"
  232. " depreciated in GRASS GIS 7.0 and will be removed"
  233. " in version 7.1.") % opt)
  234. elif opt.endswith('_'):
  235. opt = opt[:-1]
  236. args.append("%s=%s" % (opt, _make_val(val)))
  237. return args
  238. def handle_errors(returncode, result, args, kwargs):
  239. if returncode == 0:
  240. return result
  241. handler = kwargs.get('errors', 'raise')
  242. if handler.lower() == 'ignore':
  243. return result
  244. elif handler.lower() == 'status':
  245. return returncode
  246. elif handler.lower() == 'exit':
  247. sys.exit(1)
  248. else:
  249. # TODO: construction of the whole command is far from perfect
  250. args = make_command(*args, **kwargs)
  251. raise CalledModuleError(module=None, code=repr(args),
  252. returncode=returncode)
  253. def start_command(prog, flags="", overwrite=False, quiet=False,
  254. verbose=False, **kwargs):
  255. """Returns a Popen object with the command created by make_command.
  256. Accepts any of the arguments which Popen() accepts apart from "args"
  257. and "shell".
  258. >>> p = start_command("g.gisenv", stdout=subprocess.PIPE)
  259. >>> print p # doctest: +ELLIPSIS
  260. <...Popen object at 0x...>
  261. >>> print p.communicate()[0] # doctest: +SKIP
  262. GISDBASE='/opt/grass-data';
  263. LOCATION_NAME='spearfish60';
  264. MAPSET='glynn';
  265. GRASS_DB_ENCODING='ascii';
  266. GUI='text';
  267. MONITOR='x0';
  268. If the module parameter is the same as Python keyword, add
  269. underscore at the end of the parameter. For example, use
  270. ``lambda_=1.6`` instead of ``lambda=1.6``.
  271. :param str prog: GRASS module
  272. :param str flags: flags to be used (given as a string)
  273. :param bool overwrite: True to enable overwriting the output (<tt>--o</tt>)
  274. :param bool quiet: True to run quietly (<tt>--q</tt>)
  275. :param bool verbose: True to run verbosely (<tt>--v</tt>)
  276. :param kwargs: module's parameters
  277. :return: Popen object
  278. """
  279. options = {}
  280. popts = {}
  281. for opt, val in kwargs.iteritems():
  282. if opt in _popen_args:
  283. popts[opt] = val
  284. else:
  285. if isinstance(val, unicode):
  286. val = encode(val)
  287. options[opt] = val
  288. args = make_command(prog, flags, overwrite, quiet, verbose, **options)
  289. if debug_level() > 0:
  290. sys.stderr.write("D1/%d: %s.start_command(): %s\n" % (debug_level(),
  291. __name__,
  292. ' '.join(args)))
  293. sys.stderr.flush()
  294. return Popen(args, **popts)
  295. def run_command(*args, **kwargs):
  296. """Passes all arguments to start_command(), then waits for the process to
  297. complete, returning its exit code. Similar to subprocess.check_call(), but
  298. with the make_command() interface.
  299. :param list args: list of unnamed arguments (see start_command() for details)
  300. :param list kwargs: list of named arguments (see start_command() for details)
  301. :return: exit code (0 for success)
  302. """
  303. ps = start_command(*args, **kwargs)
  304. returncode = ps.wait()
  305. return handle_errors(returncode, returncode, args, kwargs)
  306. def pipe_command(*args, **kwargs):
  307. """Passes all arguments to start_command(), but also adds
  308. "stdout = PIPE". Returns the Popen object.
  309. >>> p = pipe_command("g.gisenv")
  310. >>> print p # doctest: +ELLIPSIS
  311. <....Popen object at 0x...>
  312. >>> print p.communicate()[0] # doctest: +SKIP
  313. GISDBASE='/opt/grass-data';
  314. LOCATION_NAME='spearfish60';
  315. MAPSET='glynn';
  316. GRASS_DB_ENCODING='ascii';
  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. :param str msg: error message to be displayed
  447. """
  448. message(msg, flag='e')
  449. def fatal(msg):
  450. """Display an error message using `g.message -e`, then abort
  451. Raise exception when raise_on_error is 'True'.
  452. :param str msg: error message to be displayed
  453. """
  454. global raise_on_error
  455. if raise_on_error:
  456. raise ScriptError(msg)
  457. error(msg)
  458. sys.exit(1)
  459. def set_raise_on_error(raise_exp=True):
  460. """Define behaviour on fatal error (fatal() called)
  461. :param bool raise_exp: True to raise ScriptError instead of calling
  462. sys.exit(1) in fatal()
  463. :return: current status
  464. """
  465. global raise_on_error
  466. tmp_raise = raise_on_error
  467. raise_on_error = raise_exp
  468. return tmp_raise
  469. def get_raise_on_error():
  470. """Return True if a ScriptError exception is raised instead of calling
  471. sys.exit(1) in case a fatal error was invoked with fatal()
  472. """
  473. global raise_on_error
  474. return raise_on_error
  475. # interface to g.parser
  476. def _parse_opts(lines):
  477. options = {}
  478. flags = {}
  479. for line in lines:
  480. if not line:
  481. break
  482. try:
  483. [var, val] = line.split('=', 1)
  484. except:
  485. raise SyntaxError("invalid output from g.parser: %s" % line)
  486. if var.startswith('flag_'):
  487. flags[var[5:]] = bool(int(val))
  488. elif var.startswith('opt_'):
  489. options[var[4:]] = val
  490. elif var in ['GRASS_OVERWRITE', 'GRASS_VERBOSE']:
  491. os.environ[var] = val
  492. else:
  493. raise SyntaxError("invalid output from g.parser: %s" % line)
  494. return (options, flags)
  495. def parser():
  496. """Interface to g.parser, intended to be run from the top-level, e.g.:
  497. ::
  498. if __name__ == "__main__":
  499. options, flags = grass.parser()
  500. main()
  501. Thereafter, the global variables "options" and "flags" will be
  502. dictionaries containing option/flag values, keyed by lower-case
  503. option/flag names. The values in "options" are strings, those in
  504. "flags" are Python booleans.
  505. """
  506. if not os.getenv("GISBASE"):
  507. print >> sys.stderr, "You must be in GRASS GIS to run this program."
  508. sys.exit(1)
  509. cmdline = [basename(sys.argv[0])]
  510. cmdline += ['"' + arg + '"' for arg in sys.argv[1:]]
  511. os.environ['CMDLINE'] = ' '.join(cmdline)
  512. argv = sys.argv[:]
  513. name = argv[0]
  514. if not os.path.isabs(name):
  515. if os.sep in name or (os.altsep and os.altsep in name):
  516. argv[0] = os.path.abspath(name)
  517. else:
  518. argv[0] = os.path.join(sys.path[0], name)
  519. prog = "g.parser.exe" if sys.platform == "win32" else "g.parser"
  520. p = subprocess.Popen([prog, '-n'] + argv, stdout=subprocess.PIPE)
  521. s = p.communicate()[0]
  522. lines = s.split('\0')
  523. if not lines or lines[0] != "@ARGS_PARSED@":
  524. sys.stdout.write(s)
  525. sys.exit(p.returncode)
  526. return _parse_opts(lines[1:])
  527. # interface to g.tempfile
  528. def tempfile(create=True):
  529. """Returns the name of a temporary file, created with g.tempfile.
  530. :param bool create: True to create a file
  531. :return: path to a tmp file
  532. """
  533. flags = ''
  534. if not create:
  535. flags += 'd'
  536. return read_command("g.tempfile", flags=flags, pid=os.getpid()).strip()
  537. def tempdir():
  538. """Returns the name of a temporary dir, created with g.tempfile."""
  539. tmp = tempfile(create=False)
  540. os.mkdir(tmp)
  541. return tmp
  542. def _compare_projection(dic):
  543. """Check if projection has some possibility of duplicate names like
  544. Universal Transverse Mercator and Universe Transverse Mercator and
  545. unify them
  546. :param dic: The dictionary containing information about projection
  547. :return: The dictionary with the new values if needed
  548. """
  549. # the lookup variable is a list of list, each list contains all the
  550. # possible name for a projection system
  551. lookup = [['Universal Transverse Mercator', 'Universe Transverse Mercator']]
  552. for lo in lookup:
  553. for n in range(len(dic['name'])):
  554. if dic['name'][n] in lo:
  555. dic['name'][n] = lo[0]
  556. return dic
  557. def _compare_units(dic):
  558. """Check if units has some possibility of duplicate names like
  559. meter and metre and unify them
  560. :param dic: The dictionary containing information about units
  561. :return: The dictionary with the new values if needed
  562. """
  563. # the lookup variable is a list of list, each list contains all the
  564. # possible name for a units
  565. lookup = [['meter', 'metre'], ['meters', 'metres'], ['kilometer',
  566. 'kilometre'], ['kilometers', 'kilometres']]
  567. for l in lookup:
  568. for n in range(len(dic['unit'])):
  569. if dic['unit'][n].lower() in l:
  570. dic['unit'][n] = l[0]
  571. for n in range(len(dic['units'])):
  572. if dic['units'][n].lower() in l:
  573. dic['units'][n] = l[0]
  574. return dic
  575. def _text_to_key_value_dict(filename, sep=":", val_sep=",", checkproj=False,
  576. checkunits=False):
  577. """Convert a key-value text file, where entries are separated by newlines
  578. and the key and value are separated by `sep', into a key-value dictionary
  579. and discover/use the correct data types (float, int or string) for values.
  580. :param str filename: The name or name and path of the text file to convert
  581. :param str sep: The character that separates the keys and values, default
  582. is ":"
  583. :param str val_sep: The character that separates the values of a single
  584. key, default is ","
  585. :param bool checkproj: True if it has to check some information about
  586. projection system
  587. :param bool checkproj: True if it has to check some information about units
  588. :return: The dictionary
  589. A text file with this content:
  590. ::
  591. a: Hello
  592. b: 1.0
  593. c: 1,2,3,4,5
  594. d : hello,8,0.1
  595. Will be represented as this dictionary:
  596. ::
  597. {'a': ['Hello'], 'c': [1, 2, 3, 4, 5], 'b': [1.0], 'd': ['hello', 8, 0.1]}
  598. """
  599. text = open(filename, "r").readlines()
  600. kvdict = KeyValue()
  601. for line in text:
  602. if line.find(sep) >= 0:
  603. key, value = line.split(sep)
  604. key = key.strip()
  605. value = value.strip()
  606. else:
  607. # Jump over empty values
  608. continue
  609. values = value.split(val_sep)
  610. value_list = []
  611. for value in values:
  612. not_float = False
  613. not_int = False
  614. # Convert values into correct types
  615. # We first try integer then float
  616. try:
  617. value_converted = int(value)
  618. except:
  619. not_int = True
  620. if not_int:
  621. try:
  622. value_converted = float(value)
  623. except:
  624. not_float = True
  625. if not_int and not_float:
  626. value_converted = value.strip()
  627. value_list.append(value_converted)
  628. kvdict[key] = value_list
  629. if checkproj:
  630. kvdict = _compare_projection(kvdict)
  631. if checkunits:
  632. kvdict = _compare_units(kvdict)
  633. return kvdict
  634. def compare_key_value_text_files(filename_a, filename_b, sep=":",
  635. val_sep=",", precision=0.000001,
  636. proj=False, units=False):
  637. """Compare two key-value text files
  638. This method will print a warning in case keys that are present in the first
  639. file are not present in the second one.
  640. The comparison method tries to convert the values into their native format
  641. (float, int or string) to allow correct comparison.
  642. An example key-value text file may have this content:
  643. ::
  644. a: Hello
  645. b: 1.0
  646. c: 1,2,3,4,5
  647. d : hello,8,0.1
  648. :param str filename_a: name of the first key-value text file
  649. :param str filenmae_b: name of the second key-value text file
  650. :param str sep: character that separates the keys and values, default is ":"
  651. :param str val_sep: character that separates the values of a single key, default is ","
  652. :param double precision: precision with which the floating point values are compared
  653. :param bool proj: True if it has to check some information about projection system
  654. :param bool units: True if it has to check some information about units
  655. :return: True if full or almost identical, False if different
  656. """
  657. dict_a = _text_to_key_value_dict(filename_a, sep, checkproj=proj,
  658. checkunits=units)
  659. dict_b = _text_to_key_value_dict(filename_b, sep, checkproj=proj,
  660. checkunits=units)
  661. if sorted(dict_a.keys()) != sorted(dict_b.keys()):
  662. return False
  663. # We compare matching keys
  664. for key in dict_a.keys():
  665. # Floating point values must be handled separately
  666. if isinstance(dict_a[key], float) and isinstance(dict_b[key], float):
  667. if abs(dict_a[key] - dict_b[key]) > precision:
  668. return False
  669. elif isinstance(dict_a[key], float) or isinstance(dict_b[key], float):
  670. warning(_("Mixing value types. Will try to compare after "
  671. "integer conversion"))
  672. return int(dict_a[key]) == int(dict_b[key])
  673. elif key == "+towgs84":
  674. # We compare the sum of the entries
  675. if abs(sum(dict_a[key]) - sum(dict_b[key])) > precision:
  676. return False
  677. else:
  678. if dict_a[key] != dict_b[key]:
  679. return False
  680. return True
  681. # interface to g.gisenv
  682. def gisenv():
  683. """Returns the output from running g.gisenv (with no arguments), as a
  684. dictionary. Example:
  685. >>> env = gisenv()
  686. >>> print env['GISDBASE'] # doctest: +SKIP
  687. /opt/grass-data
  688. :return: list of GRASS variables
  689. """
  690. s = read_command("g.gisenv", flags='n')
  691. return parse_key_val(s)
  692. # interface to g.region
  693. def locn_is_latlong():
  694. """Tests if location is lat/long. Value is obtained
  695. by checking the "g.region -pu" projection code.
  696. :return: True for a lat/long region, False otherwise
  697. """
  698. s = read_command("g.region", flags='pu')
  699. kv = parse_key_val(s, ':')
  700. if kv['projection'].split(' ')[0] == '3':
  701. return True
  702. else:
  703. return False
  704. def region(region3d=False, complete=False):
  705. """Returns the output from running "g.region -gu", as a
  706. dictionary. Example:
  707. :param bool region3d: True to get 3D region
  708. :param bool complete:
  709. >>> curent_region = region()
  710. >>> # obtain n, s, e and w values
  711. >>> [curent_region[key] for key in "nsew"] # doctest: +ELLIPSIS
  712. [..., ..., ..., ...]
  713. >>> # obtain ns and ew resulutions
  714. >>> (curent_region['nsres'], curent_region['ewres']) # doctest: +ELLIPSIS
  715. (..., ...)
  716. :return: dictionary of region values
  717. """
  718. flgs = 'gu'
  719. if region3d:
  720. flgs += '3'
  721. if complete:
  722. flgs += 'cep'
  723. s = read_command("g.region", flags=flgs)
  724. reg = parse_key_val(s, val_type=float)
  725. for k in ['rows', 'cols', 'cells',
  726. 'rows3', 'cols3', 'cells3', 'depths']:
  727. if k not in reg:
  728. continue
  729. reg[k] = int(reg[k])
  730. return reg
  731. def region_env(region3d=False, **kwargs):
  732. """Returns region settings as a string which can used as
  733. GRASS_REGION environmental variable.
  734. If no 'kwargs' are given then the current region is used. Note
  735. that this function doesn't modify the current region!
  736. See also use_temp_region() for alternative method how to define
  737. temporary region used for raster-based computation.
  738. :param bool region3d: True to get 3D region
  739. :param kwargs: g.region's parameters like 'rast', 'vect' or 'region'
  740. ::
  741. os.environ['GRASS_REGION'] = grass.region_env(region='detail')
  742. grass.mapcalc('map=1', overwrite=True)
  743. os.environ.pop('GRASS_REGION')
  744. :return: string with region values
  745. :return: empty string on error
  746. """
  747. # read proj/zone from WIND file
  748. env = gisenv()
  749. windfile = os.path.join(env['GISDBASE'], env['LOCATION_NAME'],
  750. env['MAPSET'], "WIND")
  751. fd = open(windfile, "r")
  752. grass_region = ''
  753. for line in fd.readlines():
  754. key, value = map(lambda x: x.strip(), line.split(":", 1))
  755. if kwargs and key not in ('proj', 'zone'):
  756. continue
  757. if not kwargs and not region3d and \
  758. key in ('top', 'bottom', 'cols3', 'rows3',
  759. 'depths', 'e-w resol3', 'n-s resol3', 't-b resol'):
  760. continue
  761. grass_region += '%s: %s;' % (key, value)
  762. if not kwargs: # return current region
  763. return grass_region
  764. # read other values from `g.region -gu`
  765. flgs = 'ug'
  766. if region3d:
  767. flgs += '3'
  768. s = read_command('g.region', flags=flgs, **kwargs)
  769. if not s:
  770. return ''
  771. reg = parse_key_val(s)
  772. kwdata = [('north', 'n'),
  773. ('south', 's'),
  774. ('east', 'e'),
  775. ('west', 'w'),
  776. ('cols', 'cols'),
  777. ('rows', 'rows'),
  778. ('e-w resol', 'ewres'),
  779. ('n-s resol', 'nsres')]
  780. if region3d:
  781. kwdata += [('top', 't'),
  782. ('bottom', 'b'),
  783. ('cols3', 'cols3'),
  784. ('rows3', 'rows3'),
  785. ('depths', 'depths'),
  786. ('e-w resol3', 'ewres3'),
  787. ('n-s resol3', 'nsres3'),
  788. ('t-b resol', 'tbres')]
  789. for wkey, rkey in kwdata:
  790. grass_region += '%s: %s;' % (wkey, reg[rkey])
  791. return grass_region
  792. def use_temp_region():
  793. """Copies the current region to a temporary region with "g.region save=",
  794. then sets WIND_OVERRIDE to refer to that region. Installs an atexit
  795. handler to delete the temporary region upon termination.
  796. """
  797. name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
  798. run_command("g.region", save=name, overwrite=True)
  799. os.environ['WIND_OVERRIDE'] = name
  800. atexit.register(del_temp_region)
  801. def del_temp_region():
  802. """Unsets WIND_OVERRIDE and removes any region named by it."""
  803. try:
  804. name = os.environ.pop('WIND_OVERRIDE')
  805. run_command("g.remove", flags='f', quiet=True, type='region', name=name)
  806. except:
  807. pass
  808. # interface to g.findfile
  809. def find_file(name, element='cell', mapset=None):
  810. """Returns the output from running g.findfile as a
  811. dictionary. Example:
  812. >>> result = find_file('elevation', element='cell')
  813. >>> print result['fullname']
  814. elevation@PERMANENT
  815. >>> print result['file'] # doctest: +ELLIPSIS
  816. /.../PERMANENT/cell/elevation
  817. :param str name: file name
  818. :param str element: element type (default 'cell')
  819. :param str mapset: mapset name (default all mapsets in search path)
  820. :return: parsed output of g.findfile
  821. """
  822. if element == 'raster' or element == 'rast':
  823. verbose(_('Element type should be "cell" and not "%s"') % element)
  824. element = 'cell'
  825. # g.findfile returns non-zero when file was not found
  826. # se we ignore return code and just focus on stdout
  827. process = start_command('g.findfile', flags='n',
  828. element=element, file=name, mapset=mapset,
  829. stdout=PIPE)
  830. stdout = process.communicate()[0]
  831. return parse_key_val(stdout)
  832. # interface to g.list
  833. def list_strings(type, pattern=None, mapset=None, exclude=None, flag=''):
  834. """List of elements as strings.
  835. Returns the output from running g.list, as a list of qualified
  836. names.
  837. :param str type: element type (rast, vect, rast3d, region, ...)
  838. :param str pattern: pattern string
  839. :param str mapset: mapset name (if not given use search path)
  840. :param str exclude: pattern string to exclude maps from the research
  841. :param str flag: pattern type: 'r' (basic regexp), 'e' (extended regexp),
  842. or '' (glob pattern)
  843. :return: list of elements
  844. """
  845. if type == 'raster' or type == 'cell':
  846. verbose(_('Element type should be "rast" and not "%s"') % type)
  847. type = 'rast'
  848. result = list()
  849. for line in read_command("g.list",
  850. quiet=True,
  851. flags='m' + flag,
  852. type=type,
  853. pattern=pattern,
  854. exclude=exclude,
  855. mapset=mapset).splitlines():
  856. result.append(line.strip())
  857. return result
  858. def list_pairs(type, pattern=None, mapset=None, exclude=None, flag=''):
  859. """List of elements as pairs
  860. Returns the output from running g.list, as a list of
  861. (name, mapset) pairs
  862. :param str type: element type (rast, vect, rast3d, region, ...)
  863. :param str pattern: pattern string
  864. :param str mapset: mapset name (if not given use search path)
  865. :param str exclude: pattern string to exclude maps from the research
  866. :param str flag: pattern type: 'r' (basic regexp), 'e' (extended regexp),
  867. or '' (glob pattern)
  868. :return: list of elements
  869. """
  870. return [tuple(map.split('@', 1)) for map in list_strings(type, pattern,
  871. mapset, exclude,
  872. flag)]
  873. def list_grouped(type, pattern=None, check_search_path=True, exclude=None,
  874. flag=''):
  875. """List of elements grouped by mapsets.
  876. Returns the output from running g.list, as a dictionary where the
  877. keys are mapset names and the values are lists of maps in that
  878. mapset. Example:
  879. >>> list_grouped('vect', pattern='*roads*')['PERMANENT']
  880. ['railroads', 'roadsmajor']
  881. :param str type: element type (rast, vect, rast3d, region, ...) or list of elements
  882. :param str pattern: pattern string
  883. :param str check_search_path: True to add mapsets for the search path
  884. with no found elements
  885. :param str exclude: pattern string to exclude maps from the research
  886. :param str flag: pattern type: 'r' (basic regexp), 'e' (extended regexp),
  887. or '' (glob pattern)
  888. :return: directory of mapsets/elements
  889. """
  890. if isinstance(type, python_types.StringTypes) or len(type) == 1:
  891. types = [type]
  892. store_types = False
  893. else:
  894. types = type
  895. store_types = True
  896. flag += 't'
  897. for i in range(len(types)):
  898. if types[i] == 'raster' or types[i] == 'cell':
  899. verbose(_('Element type should be "rast" and not "%s"') % types[i])
  900. types[i] = 'rast'
  901. result = {}
  902. if check_search_path:
  903. for mapset in mapsets(search_path=True):
  904. if store_types:
  905. result[mapset] = {}
  906. else:
  907. result[mapset] = []
  908. mapset = None
  909. for line in read_command("g.list", quiet=True, flags="m" + flag,
  910. type=types, pattern=pattern, exclude=exclude).splitlines():
  911. try:
  912. name, mapset = line.split('@')
  913. except ValueError:
  914. warning(_("Invalid element '%s'") % line)
  915. continue
  916. if store_types:
  917. type_, name = name.split('/')
  918. if mapset in result:
  919. if type_ in result[mapset]:
  920. result[mapset][type_].append(name)
  921. else:
  922. result[mapset][type_] = [name, ]
  923. else:
  924. result[mapset] = {type_: [name, ]}
  925. else:
  926. if mapset in result:
  927. result[mapset].append(name)
  928. else:
  929. result[mapset] = [name, ]
  930. return result
  931. # color parsing
  932. named_colors = {
  933. "white": (1.00, 1.00, 1.00),
  934. "black": (0.00, 0.00, 0.00),
  935. "red": (1.00, 0.00, 0.00),
  936. "green": (0.00, 1.00, 0.00),
  937. "blue": (0.00, 0.00, 1.00),
  938. "yellow": (1.00, 1.00, 0.00),
  939. "magenta": (1.00, 0.00, 1.00),
  940. "cyan": (0.00, 1.00, 1.00),
  941. "aqua": (0.00, 0.75, 0.75),
  942. "grey": (0.75, 0.75, 0.75),
  943. "gray": (0.75, 0.75, 0.75),
  944. "orange": (1.00, 0.50, 0.00),
  945. "brown": (0.75, 0.50, 0.25),
  946. "purple": (0.50, 0.00, 1.00),
  947. "violet": (0.50, 0.00, 1.00),
  948. "indigo": (0.00, 0.50, 1.00)}
  949. def parse_color(val, dflt=None):
  950. """Parses the string "val" as a GRASS colour, which can be either one of
  951. the named colours or an R:G:B tuple e.g. 255:255:255. Returns an
  952. (r,g,b) triple whose components are floating point values between 0
  953. and 1. Example:
  954. >>> parse_color("red")
  955. (1.0, 0.0, 0.0)
  956. >>> parse_color("255:0:0")
  957. (1.0, 0.0, 0.0)
  958. :param val: color value
  959. :param dflt: default color value
  960. :return: tuple RGB
  961. """
  962. if val in named_colors:
  963. return named_colors[val]
  964. vals = val.split(':')
  965. if len(vals) == 3:
  966. return tuple(float(v) / 255 for v in vals)
  967. return dflt
  968. # check GRASS_OVERWRITE
  969. def overwrite():
  970. """Return True if existing files may be overwritten"""
  971. owstr = 'GRASS_OVERWRITE'
  972. return owstr in os.environ and os.environ[owstr] != '0'
  973. # check GRASS_VERBOSE
  974. def verbosity():
  975. """Return the verbosity level selected by GRASS_VERBOSE"""
  976. vbstr = os.getenv('GRASS_VERBOSE')
  977. if vbstr:
  978. return int(vbstr)
  979. else:
  980. return 2
  981. ## various utilities, not specific to GRASS
  982. def find_program(pgm, *args):
  983. """Attempt to run a program, with optional arguments.
  984. You must call the program in a way that will return a successful
  985. exit code. For GRASS modules this means you need to pass it some
  986. valid CLI option, like "--help". For other programs a common
  987. valid do-little option is usually "--version".
  988. Example:
  989. >>> find_program('r.sun', '--help')
  990. True
  991. >>> find_program('ls', '--version')
  992. True
  993. :param str pgm: program name
  994. :param args: list of arguments
  995. :return: False if the attempt failed due to a missing executable
  996. or non-zero return code
  997. :return: True otherwise
  998. """
  999. nuldev = file(os.devnull, 'w+')
  1000. try:
  1001. # TODO: the doc or impl is not correct, any return code is accepted
  1002. call([pgm] + list(args), stdin = nuldev, stdout = nuldev, stderr = nuldev)
  1003. found = True
  1004. except:
  1005. found = False
  1006. nuldev.close()
  1007. return found
  1008. # interface to g.mapsets
  1009. def mapsets(search_path=False):
  1010. """List available mapsets
  1011. :param bool search_path: True to list mapsets only in search path
  1012. :return: list of mapsets
  1013. """
  1014. if search_path:
  1015. flags = 'p'
  1016. else:
  1017. flags = 'l'
  1018. mapsets = read_command('g.mapsets',
  1019. flags=flags,
  1020. sep='newline',
  1021. quiet=True)
  1022. if not mapsets:
  1023. fatal(_("Unable to list mapsets"))
  1024. return mapsets.splitlines()
  1025. # interface to `g.proj -c`
  1026. def create_location(dbase, location, epsg=None, proj4=None, filename=None,
  1027. wkt=None, datum=None, datum_trans=None, desc=None,
  1028. overwrite=False):
  1029. """Create new location
  1030. Raise ScriptError on error.
  1031. :param str dbase: path to GRASS database
  1032. :param str location: location name to create
  1033. :param epsg: if given create new location based on EPSG code
  1034. :param proj4: if given create new location based on Proj4 definition
  1035. :param str filename: if given create new location based on georeferenced file
  1036. :param str wkt: if given create new location based on WKT definition
  1037. (path to PRJ file)
  1038. :param datum: GRASS format datum code
  1039. :param datum_trans: datum transformation parameters (used for epsg and proj4)
  1040. :param desc: description of the location (creates MYNAME file)
  1041. :param bool overwrite: True to overwrite location if exists(WARNING:
  1042. ALL DATA from existing location ARE DELETED!)
  1043. """
  1044. gisdbase = None
  1045. if epsg or proj4 or filename or wkt:
  1046. # FIXME: changing GISDBASE mid-session is not background-job safe
  1047. gisdbase = gisenv()['GISDBASE']
  1048. run_command('g.gisenv', set='GISDBASE=%s' % dbase)
  1049. # create dbase if not exists
  1050. if not os.path.exists(dbase):
  1051. os.mkdir(dbase)
  1052. # check if location already exists
  1053. if os.path.exists(os.path.join(dbase, location)):
  1054. if not overwrite:
  1055. warning(_("Location <%s> already exists. Operation canceled.") % location)
  1056. return
  1057. else:
  1058. warning(_("Location <%s> already exists and will be overwritten") % location)
  1059. shutil.rmtree(os.path.join(dbase, location))
  1060. kwargs = dict()
  1061. if datum:
  1062. kwargs['datum'] = datum
  1063. if datum_trans:
  1064. kwargs['datum_trans'] = datum_trans
  1065. if epsg:
  1066. ps = pipe_command('g.proj', quiet=True, flags='t', epsg=epsg,
  1067. location=location, stderr=PIPE, **kwargs)
  1068. elif proj4:
  1069. ps = pipe_command('g.proj', quiet=True, flags='t', proj4=proj4,
  1070. location=location, stderr=PIPE, **kwargs)
  1071. elif filename:
  1072. ps = pipe_command('g.proj', quiet=True, georef=filename,
  1073. location=location, stderr=PIPE)
  1074. elif wkt:
  1075. ps = pipe_command('g.proj', quiet=True, wkt=wkt, location=location,
  1076. stderr=PIPE)
  1077. else:
  1078. _create_location_xy(dbase, location)
  1079. if epsg or proj4 or filename or wkt:
  1080. error = ps.communicate()[1]
  1081. run_command('g.gisenv', set='GISDBASE=%s' % gisdbase)
  1082. if ps.returncode != 0 and error:
  1083. raise ScriptError(repr(error))
  1084. try:
  1085. fd = codecs.open(os.path.join(dbase, location, 'PERMANENT', 'MYNAME'),
  1086. encoding='utf-8', mode='w')
  1087. if desc:
  1088. fd.write(desc + os.linesep)
  1089. else:
  1090. fd.write(os.linesep)
  1091. fd.close()
  1092. except OSError as e:
  1093. raise ScriptError(repr(e))
  1094. def _create_location_xy(database, location):
  1095. """Create unprojected location
  1096. Raise ScriptError on error.
  1097. :param database: GRASS database where to create new location
  1098. :param location: location name
  1099. """
  1100. cur_dir = os.getcwd()
  1101. try:
  1102. os.chdir(database)
  1103. os.mkdir(location)
  1104. os.mkdir(os.path.join(location, 'PERMANENT'))
  1105. # create DEFAULT_WIND and WIND files
  1106. regioninfo = ['proj: 0',
  1107. 'zone: 0',
  1108. 'north: 1',
  1109. 'south: 0',
  1110. 'east: 1',
  1111. 'west: 0',
  1112. 'cols: 1',
  1113. 'rows: 1',
  1114. 'e-w resol: 1',
  1115. 'n-s resol: 1',
  1116. 'top: 1',
  1117. 'bottom: 0',
  1118. 'cols3: 1',
  1119. 'rows3: 1',
  1120. 'depths: 1',
  1121. 'e-w resol3: 1',
  1122. 'n-s resol3: 1',
  1123. 't-b resol: 1']
  1124. defwind = open(os.path.join(location,
  1125. "PERMANENT", "DEFAULT_WIND"), 'w')
  1126. for param in regioninfo:
  1127. defwind.write(param + '%s' % os.linesep)
  1128. defwind.close()
  1129. shutil.copy(os.path.join(location, "PERMANENT", "DEFAULT_WIND"),
  1130. os.path.join(location, "PERMANENT", "WIND"))
  1131. os.chdir(cur_dir)
  1132. except OSError as e:
  1133. raise ScriptError(repr(e))
  1134. # interface to g.version
  1135. def version():
  1136. """Get GRASS version as dictionary
  1137. ::
  1138. print version()
  1139. {'proj4': '4.8.0', 'geos': '3.3.5', 'libgis_revision': '52468',
  1140. 'libgis_date': '2012-07-27 22:53:30 +0200 (Fri, 27 Jul 2012)',
  1141. 'version': '7.0.svn', 'date': '2012', 'gdal': '2.0dev',
  1142. 'revision': '53670'}
  1143. """
  1144. data = parse_command('g.version', flags='rge')
  1145. for k, v in data.iteritems():
  1146. data[k.strip()] = v.replace('"', '').strip()
  1147. return data
  1148. # get debug_level
  1149. _debug_level = None
  1150. def debug_level():
  1151. global _debug_level
  1152. if _debug_level is not None:
  1153. return _debug_level
  1154. _debug_level = 0
  1155. if find_program('g.gisenv', '--help'):
  1156. _debug_level = int(gisenv().get('DEBUG', 0))
  1157. return _debug_level
  1158. def legal_name(s):
  1159. """Checks if the string contains only allowed characters.
  1160. This is the Python implementation of G_legal_filename() function.
  1161. ..note::
  1162. It is not clear when to use this function.
  1163. """
  1164. if not s or s[0] == '.':
  1165. warning(_("Illegal filename <%s>. Cannot be 'NULL' or start with " \
  1166. "'.'.") % s)
  1167. return False
  1168. illegal = [c
  1169. for c in s
  1170. if c in '/"\'@,=*~' or c <= ' ' or c >= '\177']
  1171. if illegal:
  1172. illegal = ''.join(sorted(set(illegal)))
  1173. warning(_("Illegal filename <%(s)s>. <%(il)s> not allowed.\n") % {
  1174. 's': s, 'il': illegal})
  1175. return False
  1176. return True
  1177. if __name__ == '__main__':
  1178. import doctest
  1179. doctest.testmod()