setup.py.sed 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. """!@package grass.script.setup
  2. @brief GRASS Python scripting module (setup)
  3. Setup functions to be used in Python scripts.
  4. Usage:
  5. @code
  6. from grass.script import setup as grass
  7. grass.init()
  8. ...
  9. @endcode
  10. (C) 2010-2012 by the GRASS Development Team
  11. This program is free software under the GNU General Public
  12. License (>=v2). Read the file COPYING that comes with GRASS
  13. for details.
  14. @author Martin Landa <landa.martin gmail.com>
  15. """
  16. import os
  17. import sys
  18. import tempfile as tmpfile
  19. def write_gisrc(dbase, location, mapset):
  20. """Write the gisrc file and return the gisrc path."""
  21. fd, gisrc = tmpfile.mkstemp()
  22. os.write(fd, "GISDBASE: %s\n" % dbase)
  23. os.write(fd, "LOCATION_NAME: %s\n" % location)
  24. os.write(fd, "MAPSET: %s\n" % mapset)
  25. os.close(fd)
  26. return gisrc
  27. def init(gisbase, dbase='', location='demolocation', mapset='PERMANENT'):
  28. """!Initialize system variables to run scripts without starting
  29. GRASS explicitly.
  30. User is resposible to delete gisrc file.
  31. @param gisbase path to GRASS installation
  32. @param dbase path to GRASS database (default: '')
  33. @param location location name (default: 'demolocation')
  34. @param mapset mapset within given location (default: 'PERMANENT')
  35. @return path to gisrc file
  36. """
  37. # define PATH
  38. os.environ['PATH'] += os.pathsep + os.path.join(gisbase, 'bin')
  39. os.environ['PATH'] += os.pathsep + os.path.join(gisbase, 'scripts')
  40. if sys.platform.startswith('win'): # added for winGRASS
  41. os.environ['PATH'] += os.pathsep + os.path.join(gisbase, 'extrabin')
  42. # define LD_LIBRARY_PATH
  43. if '@LD_LIBRARY_PATH_VAR@' not in os.environ:
  44. os.environ['@LD_LIBRARY_PATH_VAR@'] = ''
  45. os.environ['@LD_LIBRARY_PATH_VAR@'] += os.pathsep + os.path.join(gisbase, 'lib')
  46. os.environ['GIS_LOCK'] = str(os.getpid())
  47. # Set PYTHONPATH to find GRASS Python modules
  48. path = os.getenv('PYTHONPATH')
  49. etcpy = os.path.join(gisbase, 'etc', 'python')
  50. if path:
  51. path = etcpy + os.pathsep + path
  52. else:
  53. path = etcpy
  54. os.environ['PYTHONPATH'] = path
  55. if not dbase:
  56. dbase = gisbase
  57. os.environ['GISRC'] = write_gisrc(dbase, location, mapset)
  58. return os.environ['GISRC']