setup.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. R"""Setup, initialization, and clean-up functions
  2. Functions can be used in Python scripts to setup a GRASS environment
  3. and session without using grassXY.
  4. Usage::
  5. import os
  6. import sys
  7. import subprocess
  8. # define GRASS Database
  9. # add your path to grassdata (GRASS GIS database) directory
  10. gisdb = "~/grassdata"
  11. # the following path is the default path on MS Windows
  12. # gisdb = "~/Documents/grassdata"
  13. # specify (existing) Location and Mapset
  14. location = "nc_spm_08"
  15. mapset = "user1"
  16. # path to the GRASS GIS launch script
  17. # we assume that the GRASS GIS start script is available and on PATH
  18. # query GRASS itself for its GISBASE
  19. # (with fixes for specific platforms)
  20. # needs to be edited by the user
  21. grass8bin = "grass"
  22. if sys.platform.startswith("win"):
  23. # MS Windows
  24. grass8bin = r"C:\OSGeo4W\bin\grass.bat"
  25. # uncomment when using standalone WinGRASS installer
  26. # grass8bin = r'C:\Program Files (x86)\GRASS GIS 8.0.0\grass.bat'
  27. # this can be avoided if GRASS executable is added to PATH
  28. elif sys.platform == "darwin":
  29. # Mac OS X
  30. grass8bin = "/Applications/GRASS-8.0.app/Contents/Resources/bin/grass"
  31. # query GRASS GIS itself for its Python package path
  32. grass_cmd = [grass8bin, "--config", "python_path"]
  33. process = subprocess.run(grass_cmd, check=True, text=True, stdout=subprocess.PIPE)
  34. # define GRASS-Python environment
  35. sys.path.append(process.stdout.strip())
  36. # import (some) GRASS Python bindings
  37. import grass.script as gs
  38. import grass.script.setup as gsetup
  39. # launch session
  40. rcfile = gsetup.init(gisdb, location, mapset)
  41. # example calls
  42. gs.message("Current GRASS GIS 8 environment:")
  43. print(gs.gisenv())
  44. gs.message("Available raster maps:")
  45. for rast in gs.list_strings(type="raster"):
  46. print(rast)
  47. gs.message("Available vector maps:")
  48. for vect in gs.list_strings(type="vector"):
  49. print(vect)
  50. # clean up at the end
  51. gsetup.finish()
  52. (C) 2010-2021 by the GRASS Development Team
  53. This program is free software under the GNU General Public
  54. License (>=v2). Read the file COPYING that comes with GRASS
  55. for details.
  56. @author Martin Landa <landa.martin gmail.com>
  57. @author Vaclav Petras <wenzeslaus gmail.com>
  58. @author Markus Metz
  59. """
  60. # TODO: this should share code from lib/init/grass.py
  61. # perhaps grass.py can import without much trouble once GISBASE
  62. # is known, this would allow moving things from there, here
  63. # then this could even do locking
  64. from pathlib import Path
  65. import os
  66. import shutil
  67. import subprocess
  68. import sys
  69. import tempfile as tmpfile
  70. WINDOWS = sys.platform.startswith("win")
  71. MACOS = sys.platform.startswith("darwin")
  72. VERSION_MAJOR = "@GRASS_VERSION_MAJOR@"
  73. VERSION_MINOR = "@GRASS_VERSION_MINOR@"
  74. def write_gisrc(dbase, location, mapset):
  75. """Write the ``gisrc`` file and return its path."""
  76. gisrc = tmpfile.mktemp()
  77. with open(gisrc, "w") as rc:
  78. rc.write("GISDBASE: %s\n" % dbase)
  79. rc.write("LOCATION_NAME: %s\n" % location)
  80. rc.write("MAPSET: %s\n" % mapset)
  81. return gisrc
  82. def set_gui_path():
  83. """Insert wxPython GRASS path to sys.path."""
  84. gui_path = os.path.join(os.environ["GISBASE"], "gui", "wxpython")
  85. if gui_path and gui_path not in sys.path:
  86. sys.path.insert(0, gui_path)
  87. def get_install_path(path=None):
  88. """Get path to GRASS installation usable for setup of environmental variables.
  89. The function tries to determine path tp GRASS GIS installation so that the
  90. returned path can be used for setup of environmental variable for GRASS runtime.
  91. If the search fails, None is returned.
  92. By default, the resulting path is derived relatively from the location of the
  93. Python package (specifically this module) in the file system. This derived path
  94. is returned only if it has subdirectories called ``bin`` and ``lib``.
  95. If the parameter or certain environmental variables are set, the following
  96. attempts are made to find the path.
  97. If *path* is provided and it is an existing executable, the executable is queried
  98. for the path. Otherwise, provided *path* is returned as is.
  99. If *path* is not provided, the GISBASE environmental variable is used as the path
  100. if it exists. If GRASSBIN environmental variable exists and it is an existing
  101. executable, the executable is queried for the path.
  102. If *path* is not provided and no relevant environmental variables are set, the
  103. default relative path search is performed.
  104. If that fails and executable called ``grass`` exists, it is queried for the path.
  105. None is returned if all the attempts failed.
  106. If an existing executable is called as a subprocess is called during the search
  107. and it fails, the CalledProcessError exception is propagated from the subprocess
  108. call.
  109. """
  110. def ask_executable(arg):
  111. """Query the GRASS exectable for the path"""
  112. return subprocess.run(
  113. [arg, "--config", "path"], text=True, check=True, capture_output=True
  114. ).stdout.strip()
  115. # Exectable was provided as parameter.
  116. if path and shutil.which(path):
  117. # The path was provided by the user and it is an executable
  118. # (on path or provided with full path), so raise exception on failure.
  119. return ask_executable(path)
  120. # Presumably directory was provided.
  121. if path:
  122. return path
  123. # GISBASE is already set.
  124. env_gisbase = os.environ.get("GISBASE")
  125. if env_gisbase:
  126. return env_gisbase
  127. # Executable provided in environment (name is from grass-session).
  128. # The variable is supported (here), documented, but not widely promoted
  129. # at this point (to be re-evaluated).
  130. grass_bin = os.environ.get("GRASSBIN")
  131. if grass_bin and shutil.which(grass_bin):
  132. return ask_executable(grass_bin)
  133. # Derive the path from path to this file (Python module).
  134. # This is the standard way when there is no user-provided settings.
  135. # Uses relative path to find the right parent and then tests presence of lib
  136. # and bin. Removing 5 parts from the path works for
  137. # .../grass_install_prefix/etc/python/grass and also .../python3/dist-packages/.
  138. install_path = Path(*Path(__file__).parts[:-5])
  139. bin_path = install_path / "bin"
  140. lib_path = install_path / "lib"
  141. if bin_path.is_dir() and lib_path.is_dir():
  142. return install_path
  143. # As a last resort, try running grass command if it exists.
  144. # This is less likely give the right result than the relative path on systems
  145. # with multiple installations (where an explicit setup is likely required).
  146. # However, it allows for non-standard installations with standard command.
  147. grass_bin = "grass"
  148. if grass_bin and shutil.which(grass_bin):
  149. return ask_executable(grass_bin)
  150. return None
  151. def setup_runtime_env(gisbase):
  152. """Setup the runtime environment.
  153. Modifies the global environment (os.environ) so that GRASS modules can run.
  154. """
  155. # Accept Path objects.
  156. gisbase = os.fspath(gisbase)
  157. # Set GISBASE
  158. os.environ["GISBASE"] = gisbase
  159. # define PATH
  160. path_addition = os.pathsep + os.path.join(gisbase, "bin")
  161. path_addition += os.pathsep + os.path.join(gisbase, "scripts")
  162. if WINDOWS:
  163. path_addition += os.pathsep + os.path.join(gisbase, "extrabin")
  164. # add addons to the PATH, use GRASS_ADDON_BASE if set
  165. # copied and simplified from lib/init/grass.py
  166. addon_base = os.getenv("GRASS_ADDON_BASE")
  167. if not addon_base:
  168. if WINDOWS:
  169. config_dirname = f"GRASS{VERSION_MAJOR}"
  170. addon_base = os.path.join(os.getenv("APPDATA"), config_dirname, "addons")
  171. elif MACOS:
  172. version = f"{VERSION_MAJOR}.{VERSION_MINOR}"
  173. addon_base = os.path.join(
  174. os.getenv("HOME"), "Library", "GRASS", version, "Addons"
  175. )
  176. else:
  177. config_dirname = f".grass{VERSION_MAJOR}"
  178. addon_base = os.path.join(os.getenv("HOME"), config_dirname, "addons")
  179. os.environ["GRASS_ADDON_BASE"] = addon_base
  180. if not WINDOWS:
  181. path_addition += os.pathsep + os.path.join(addon_base, "scripts")
  182. path_addition += os.pathsep + os.path.join(addon_base, "bin")
  183. os.environ["PATH"] = path_addition + os.pathsep + os.getenv("PATH")
  184. # define LD_LIBRARY_PATH
  185. if "@LD_LIBRARY_PATH_VAR@" not in os.environ:
  186. os.environ["@LD_LIBRARY_PATH_VAR@"] = ""
  187. os.environ["@LD_LIBRARY_PATH_VAR@"] += os.pathsep + os.path.join(gisbase, "lib")
  188. # Set GRASS_PYTHON and PYTHONPATH to find GRASS Python modules
  189. if not os.getenv("GRASS_PYTHON"):
  190. if WINDOWS:
  191. os.environ["GRASS_PYTHON"] = "python3.exe"
  192. else:
  193. os.environ["GRASS_PYTHON"] = "python3"
  194. path = os.getenv("PYTHONPATH")
  195. etcpy = os.path.join(gisbase, "etc", "python")
  196. if path:
  197. path = etcpy + os.pathsep + path
  198. else:
  199. path = etcpy
  200. os.environ["PYTHONPATH"] = path
  201. def init(path, location=None, mapset=None, grass_path=None):
  202. """Initialize system variables to run GRASS modules
  203. This function is for running GRASS GIS without starting it with the
  204. standard main executable grass. No GRASS modules shall be called before
  205. call of this function but any module or user script can be called
  206. afterwards because a GRASS session has been set up. GRASS Python
  207. libraries are usable as well in general but the ones using C
  208. libraries through ``ctypes`` are not (which is caused by library
  209. path not being updated for the current process which is a common
  210. operating system limitation).
  211. When the path or specified mapset does not exist, ValueError is raised.
  212. The :func:`get_install_path` function is used to determine where
  213. the rest of GRASS files is installed. The *grass_path* parameter is
  214. passed to it if provided. If the path cannot be determined,
  215. ValueError is raised. Exceptions from the underlying function are propagated.
  216. To create a GRASS session a session file (aka gisrc file) is created.
  217. Caller is responsible for deleting the file which is normally done
  218. with the function :func:`finish`.
  219. Basic usage::
  220. # ... setup GISBASE and sys.path before import
  221. import grass.script as gs
  222. gs.setup.init(
  223. "~/grassdata/nc_spm_08/user1",
  224. grass_path="/usr/lib/grass",
  225. )
  226. # ... use GRASS modules here
  227. # end the session
  228. gs.setup.finish()
  229. The returned object is a context manager, so the ``with`` statement can be used to
  230. ensure that the session is finished (closed) at the end::
  231. # ... setup sys.path before import
  232. import grass.script as gs
  233. with gs.setup.init("~/grassdata/nc_spm_08/user1")
  234. # ... use GRASS modules here
  235. :param path: path to GRASS database
  236. :param location: location name
  237. :param mapset: mapset within given location (default: 'PERMANENT')
  238. :param grass_path: path to GRASS installation or executable
  239. :returns: reference to a session handle object which is a context manager
  240. """
  241. grass_path = get_install_path(grass_path)
  242. if not grass_path:
  243. raise ValueError(
  244. _("Parameter grass_path or GISBASE environmental variable must be set")
  245. )
  246. # We reduce the top-level imports because this is initialization code.
  247. # pylint: disable=import-outside-toplevel
  248. from grass.grassdb.checks import get_mapset_invalid_reason, is_mapset_valid
  249. from grass.grassdb.manage import resolve_mapset_path
  250. # Support ~ in the path for user home directory.
  251. path = Path(path).expanduser()
  252. # A simple existence test. The directory, whatever it is, should exist.
  253. if not path.exists():
  254. raise ValueError(_("Path '{path}' does not exist").format(path=path))
  255. # A specific message when it exists, but it is a file.
  256. if path.is_file():
  257. raise ValueError(
  258. _("Path '{path}' is a file, but a directory is needed").format(path=path)
  259. )
  260. mapset_path = resolve_mapset_path(path=path, location=location, mapset=mapset)
  261. if not is_mapset_valid(mapset_path):
  262. raise ValueError(
  263. _("Mapset {path} is not valid: {reason}").format(
  264. path=mapset_path.path,
  265. reason=get_mapset_invalid_reason(
  266. mapset_path.directory, mapset_path.location, mapset_path.mapset
  267. ),
  268. )
  269. )
  270. setup_runtime_env(grass_path)
  271. # TODO: lock the mapset?
  272. os.environ["GIS_LOCK"] = str(os.getpid())
  273. os.environ["GISRC"] = write_gisrc(
  274. mapset_path.directory, mapset_path.location, mapset_path.mapset
  275. )
  276. return SessionHandle()
  277. class SessionHandle:
  278. """Object used to manage GRASS sessions.
  279. Do not create objects of this class directly. Use the *init* function
  280. to get a session object.
  281. Basic usage::
  282. # ... setup sys.path before import as needed
  283. import grass.script as gs
  284. import grass.script.setup
  285. session = gs.setup.init("~/grassdata/nc_spm_08/user1")
  286. # ... use GRASS modules here
  287. # end the session
  288. session.finish()
  289. Context manager usage::
  290. # ... setup sys.path before import as needed
  291. import grass.script as gs
  292. import grass.script.setup
  293. with gs.setup.init("~/grassdata/nc_spm_08/user1"):
  294. # ... use GRASS modules here
  295. # session ends automatically here
  296. """
  297. def __init__(self, active=True):
  298. self._active = active
  299. @property
  300. def active(self):
  301. """True if session is active (not finished)"""
  302. return self._active
  303. def __enter__(self):
  304. """Enter the context manager context.
  305. Notably, the session is activated using the *init* function.
  306. :returns: reference to the object (self)
  307. """
  308. if not self.active:
  309. raise ValueError(
  310. "Attempt to use inactive (finished) session as a context manager"
  311. )
  312. return self
  313. def __exit__(self, type, value, traceback):
  314. """Exit the context manager context.
  315. Finishes the existing session.
  316. """
  317. self.finish()
  318. def finish(self):
  319. """Finish the session.
  320. If not used as a context manager, call explicitly to clean and close the mapset
  321. and finish the session. No GRASS modules can be called afterwards.
  322. """
  323. if not self.active:
  324. raise ValueError("Attempt to finish an already finished session")
  325. self._active = False
  326. finish()
  327. # clean-up functions when terminating a GRASS session
  328. # these fns can only be called within a valid GRASS session
  329. def clean_default_db():
  330. # clean the default db if it is sqlite
  331. from grass.script import core as gcore
  332. from grass.script import db as gdb
  333. conn = gdb.db_connection()
  334. if conn and conn["driver"] == "sqlite":
  335. # check if db exists
  336. gisenv = gcore.gisenv()
  337. database = conn["database"]
  338. database = database.replace("$GISDBASE", gisenv["GISDBASE"])
  339. database = database.replace("$LOCATION_NAME", gisenv["LOCATION_NAME"])
  340. database = database.replace("$MAPSET", gisenv["MAPSET"])
  341. if os.path.exists(database):
  342. gcore.message(_("Cleaning up default sqlite database ..."))
  343. gcore.start_command("db.execute", sql="VACUUM")
  344. # give it some time to start
  345. import time
  346. time.sleep(0.1)
  347. def call(cmd, **kwargs):
  348. """Wrapper for subprocess.call to deal with platform-specific issues"""
  349. if WINDOWS:
  350. kwargs["shell"] = True
  351. return subprocess.call(cmd, **kwargs)
  352. def clean_temp():
  353. from grass.script import core as gcore
  354. gcore.message(_("Cleaning up temporary files..."))
  355. nul = open(os.devnull, "w")
  356. gisbase = os.environ["GISBASE"]
  357. call([os.path.join(gisbase, "etc", "clean_temp")], stdout=nul)
  358. nul.close()
  359. def finish():
  360. """Terminate the GRASS session and clean up
  361. GRASS commands can no longer be used after this function has been
  362. called
  363. Basic usage::
  364. import grass.script as gs
  365. gs.setup.finish()
  366. The function is not completely symmetrical with :func:`init` because it only
  367. closes the mapset, but doesn't undo the runtime environment setup.
  368. """
  369. clean_default_db()
  370. clean_temp()
  371. # TODO: unlock the mapset?
  372. # unset the GISRC and delete the file
  373. from grass.script import utils as gutils
  374. gutils.try_remove(os.environ["GISRC"])
  375. os.environ.pop("GISRC")
  376. # remove gislock env var (not the gislock itself
  377. os.environ.pop("GIS_LOCK")