setup.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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 = 'grass70'
  22. if sys.platform.startswith('win'):
  23. # MS Windows
  24. grass7bin = r'C:\OSGeo4W\bin\grass70.bat'
  25. # uncomment when using standalone WinGRASS installer
  26. # grass7bin = r'C:\Program Files (x86)\GRASS GIS 7.0.0\grass70.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.0.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}:\n{error}"
  44. .format(cmd=' '.join(startcmd), error=err))
  45. gisbase = out.strip('\n\r')
  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. # launch session
  54. rcfile = gscript.setup.init(gisbase, gisdb, location, mapset)
  55. # example calls
  56. gscript.message('Current GRASS GIS 7 environment:')
  57. print gscript.gisenv()
  58. gscript.message('Available raster maps:')
  59. for rast in gscript.list_strings(type='raster'):
  60. print rast
  61. gscript.message('Available vector maps:')
  62. for vect in gscript.list_strings(type='vector'):
  63. print vect
  64. # delete the rcfile
  65. os.remove(rcfile)
  66. (C) 2010-2012 by the GRASS Development Team
  67. This program is free software under the GNU General Public
  68. License (>=v2). Read the file COPYING that comes with GRASS
  69. for details.
  70. @author Martin Landa <landa.martin gmail.com>
  71. @author Vaclav Petras <wenzeslaus gmail.com>
  72. """
  73. # TODO: this should share code from lib/init/grass.py
  74. # perhaps grass.py can import without much trouble once GISBASE
  75. # is known, this would allow moving things from there, here
  76. # then this could even do locking
  77. import os
  78. import sys
  79. import tempfile as tmpfile
  80. def write_gisrc(dbase, location, mapset):
  81. """Write the ``gisrc`` file and return its path."""
  82. fd, gisrc = tmpfile.mkstemp()
  83. os.write(fd, "GISDBASE: %s\n" % dbase)
  84. os.write(fd, "LOCATION_NAME: %s\n" % location)
  85. os.write(fd, "MAPSET: %s\n" % mapset)
  86. os.close(fd)
  87. return gisrc
  88. def init(gisbase, dbase='', location='demolocation', mapset='PERMANENT'):
  89. """Initialize system variables to run GRASS modules
  90. This function is for running GRASS GIS without starting it
  91. explicitly. No GRASS modules shall be called before call of this
  92. function but any module or user script can be called afterwards
  93. as if it would be called in an actual GRASS session. GRASS Python
  94. libraries are usable as well in general but the ones using
  95. C libraries through ``ctypes`` are not (which is caused by
  96. library path not being updated for the current process
  97. which is a common operating system limitation).
  98. To create a (fake) GRASS session a ``gisrc`` file is created.
  99. Caller is resposible for deleting the ``gisrc`` file.
  100. Basic usage::
  101. # ... setup GISBASE and PYTHON path
  102. grass.script as gscript
  103. gisrc = gscript.setup.init("/usr/lib/grass64",
  104. "/home/john/grassdata",
  105. "nc_spm_08", "user1")
  106. # ... use GRASS modules
  107. os.remove(gisrc)
  108. :param gisbase: path to GRASS installation
  109. :param dbase: path to GRASS database (default: '')
  110. :param location: location name (default: 'demolocation')
  111. :param mapset: mapset within given location (default: 'PERMANENT')
  112. :returns: path to ``gisrc`` file (to be deleted later)
  113. """
  114. # TODO: why we don't set GISBASE?
  115. mswin = sys.platform.startswith('win')
  116. # define PATH
  117. os.environ['PATH'] += os.pathsep + os.path.join(gisbase, 'bin')
  118. os.environ['PATH'] += os.pathsep + os.path.join(gisbase, 'scripts')
  119. if mswin: # added for winGRASS
  120. os.environ['PATH'] += os.pathsep + os.path.join(gisbase, 'extrabin')
  121. # add addons to the PATH
  122. # copied and simplified from lib/init/grass.py
  123. if mswin:
  124. config_dirname = "GRASS7"
  125. config_dir = os.path.join(os.getenv('APPDATA'), config_dirname)
  126. else:
  127. config_dirname = ".grass7"
  128. config_dir = os.path.join(os.getenv('HOME'), config_dirname)
  129. addon_base = os.path.join(config_dir, 'addons')
  130. os.environ['GRASS_ADDON_BASE'] = addon_base
  131. if not mswin:
  132. os.environ['PATH'] += os.pathsep + os.path.join(addon_base, 'scripts')
  133. # define LD_LIBRARY_PATH
  134. if '@LD_LIBRARY_PATH_VAR@' not in os.environ:
  135. os.environ['@LD_LIBRARY_PATH_VAR@'] = ''
  136. os.environ['@LD_LIBRARY_PATH_VAR@'] += os.pathsep + os.path.join(gisbase, 'lib')
  137. os.environ['GIS_LOCK'] = str(os.getpid())
  138. # Set PYTHONPATH to find GRASS Python modules
  139. # TODO: isn't this useless? user already imported this somehow
  140. path = os.getenv('PYTHONPATH')
  141. etcpy = os.path.join(gisbase, 'etc', 'python')
  142. if path:
  143. path = etcpy + os.pathsep + path
  144. else:
  145. path = etcpy
  146. os.environ['PYTHONPATH'] = path
  147. # TODO: isn't this contra-productive? may fail soon since we cannot
  148. # write to the installation (applies also to defaults for Location
  149. # and mapset) I don't see what would be the use case here.
  150. if not dbase:
  151. dbase = gisbase
  152. os.environ['GISRC'] = write_gisrc(dbase, location, mapset)
  153. return os.environ['GISRC']