setup.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. """Setup and initialization functions
  2. Function can be used in Python scripts to setup a GRASS environment
  3. without starting an actual GRASS session.
  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 = os.path.join(os.path.expanduser("~"), "grassdata")
  11. # the following path is the default path on MS Windows
  12. # gisdb = os.path.join(os.path.expanduser("~"), "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. grass7bin = 'grass77'
  22. if sys.platform.startswith('win'):
  23. # MS Windows
  24. grass7bin = r'C:\OSGeo4W\bin\grass77.bat'
  25. # uncomment when using standalone WinGRASS installer
  26. # grass7bin = r'C:\Program Files (x86)\GRASS GIS 7.2.0\grass77.bat'
  27. # this can be avoided if GRASS executable is added to PATH
  28. elif sys.platform == 'darwin':
  29. # Mac OS X
  30. # TODO: this have to be checked, maybe unix way is good enough
  31. grass7bin = '/Applications/GRASS/GRASS-7.7.app/'
  32. # query GRASS GIS itself for its GISBASE
  33. startcmd = [grass7bin, '--config', 'path']
  34. try:
  35. p = subprocess.Popen(startcmd, shell=False,
  36. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  37. out, err = p.communicate()
  38. except OSError as error:
  39. sys.exit("ERROR: Cannot find GRASS GIS start script"
  40. " {cmd}: {error}".format(cmd=startcmd[0], error=error))
  41. if p.returncode != 0:
  42. sys.exit("ERROR: Issues running GRASS GIS start script"
  43. " {cmd}: {error}"
  44. .format(cmd=' '.join(startcmd), error=err))
  45. gisbase = out.strip(os.linesep)
  46. # set GISBASE environment variable
  47. os.environ['GISBASE'] = gisbase
  48. # define GRASS-Python environment
  49. grass_pydir = os.path.join(gisbase, "etc", "python")
  50. sys.path.append(grass_pydir)
  51. # import (some) GRASS Python bindings
  52. import grass.script as gscript
  53. import grass.script.setup as gsetup
  54. # launch session
  55. rcfile = gsetup.init(gisbase, gisdb, location, mapset)
  56. # example calls
  57. gscript.message('Current GRASS GIS 7 environment:')
  58. print gscript.gisenv()
  59. gscript.message('Available raster maps:')
  60. for rast in gscript.list_strings(type='raster'):
  61. print rast
  62. gscript.message('Available vector maps:')
  63. for vect in gscript.list_strings(type='vector'):
  64. print vect
  65. # delete the rcfile
  66. os.remove(rcfile)
  67. (C) 2010-2012 by the GRASS Development Team
  68. This program is free software under the GNU General Public
  69. License (>=v2). Read the file COPYING that comes with GRASS
  70. for details.
  71. @author Martin Landa <landa.martin gmail.com>
  72. @author Vaclav Petras <wenzeslaus gmail.com>
  73. """
  74. # TODO: this should share code from lib/init/grass.py
  75. # perhaps grass.py can import without much trouble once GISBASE
  76. # is known, this would allow moving things from there, here
  77. # then this could even do locking
  78. import os
  79. import sys
  80. import tempfile as tmpfile
  81. def write_gisrc(dbase, location, mapset):
  82. """Write the ``gisrc`` file and return its path."""
  83. gisrc = tmpfile.mktemp()
  84. with open(gisrc, 'w') as rc:
  85. rc.write("GISDBASE: %s\n" % dbase)
  86. rc.write("LOCATION_NAME: %s\n" % location)
  87. rc.write("MAPSET: %s\n" % mapset)
  88. return gisrc
  89. def set_gui_path():
  90. """Insert wxPython GRASS path to sys.path."""
  91. gui_path = os.path.join(os.environ['GISBASE'], 'gui', 'wxpython')
  92. if gui_path and gui_path not in sys.path:
  93. sys.path.insert(0, gui_path)
  94. # TODO: there should be a function to do the clean up
  95. # (unset the GISRC and delete the file)
  96. def init(gisbase, dbase='', location='demolocation', mapset='PERMANENT'):
  97. """Initialize system variables to run GRASS modules
  98. This function is for running GRASS GIS without starting it
  99. explicitly. No GRASS modules shall be called before call of this
  100. function but any module or user script can be called afterwards
  101. as if it would be called in an actual GRASS session. GRASS Python
  102. libraries are usable as well in general but the ones using
  103. C libraries through ``ctypes`` are not (which is caused by
  104. library path not being updated for the current process
  105. which is a common operating system limitation).
  106. To create a (fake) GRASS session a ``gisrc`` file is created.
  107. Caller is responsible for deleting the ``gisrc`` file.
  108. Basic usage::
  109. # ... setup GISBASE and PYTHON path before import
  110. import grass.script as gscript
  111. gisrc = gscript.setup.init("/usr/bin/grass7",
  112. "/home/john/grassdata",
  113. "nc_spm_08", "user1")
  114. # ... use GRASS modules here
  115. # remove the session's gisrc file to end the session
  116. os.remove(gisrc)
  117. :param gisbase: path to GRASS installation
  118. :param dbase: path to GRASS database (default: '')
  119. :param location: location name (default: 'demolocation')
  120. :param mapset: mapset within given location (default: 'PERMANENT')
  121. :returns: path to ``gisrc`` file (to be deleted later)
  122. """
  123. # TODO: why we don't set GISBASE?
  124. mswin = sys.platform.startswith('win')
  125. # define PATH
  126. os.environ['PATH'] += os.pathsep + os.path.join(gisbase, 'bin')
  127. os.environ['PATH'] += os.pathsep + os.path.join(gisbase, 'scripts')
  128. if mswin: # added for winGRASS
  129. os.environ['PATH'] += os.pathsep + os.path.join(gisbase, 'extrabin')
  130. # add addons to the PATH
  131. # copied and simplified from lib/init/grass.py
  132. if mswin:
  133. config_dirname = "GRASS7"
  134. config_dir = os.path.join(os.getenv('APPDATA'), config_dirname)
  135. else:
  136. config_dirname = ".grass7"
  137. config_dir = os.path.join(os.getenv('HOME'), config_dirname)
  138. addon_base = os.path.join(config_dir, 'addons')
  139. os.environ['GRASS_ADDON_BASE'] = addon_base
  140. if not mswin:
  141. os.environ['PATH'] += os.pathsep + os.path.join(addon_base, 'scripts')
  142. os.environ['PATH'] += os.pathsep + os.path.join(addon_base, 'bin')
  143. # define LD_LIBRARY_PATH
  144. if '@LD_LIBRARY_PATH_VAR@' not in os.environ:
  145. os.environ['@LD_LIBRARY_PATH_VAR@'] = ''
  146. os.environ['@LD_LIBRARY_PATH_VAR@'] += os.pathsep + os.path.join(gisbase, 'lib')
  147. os.environ['GIS_LOCK'] = str(os.getpid())
  148. # Set GRASS_PYTHON and PYTHONPATH to find GRASS Python modules
  149. if not os.getenv('GRASS_PYTHON'):
  150. if sys.platform == 'win32':
  151. os.environ['GRASS_PYTHON'] = "python.exe"
  152. else:
  153. os.environ['GRASS_PYTHON'] = "python"
  154. path = os.getenv('PYTHONPATH')
  155. etcpy = os.path.join(gisbase, 'etc', 'python')
  156. if path:
  157. path = etcpy + os.pathsep + path
  158. else:
  159. path = etcpy
  160. os.environ['PYTHONPATH'] = path
  161. # TODO: isn't this contra-productive? may fail soon since we cannot
  162. # write to the installation (applies also to defaults for Location
  163. # and mapset) I don't see what would be the use case here.
  164. if not dbase:
  165. dbase = gisbase
  166. os.environ['GISRC'] = write_gisrc(dbase, location, mapset)
  167. return os.environ['GISRC']