User Tools

Site Tools


python:howto:grass-setup

Setting up GRASS in Python scripts

QGIS and SEXTANTE are using the command line (cli) method to execute GRASS commands. This is easy to handle and you can use the commands and put them into your scripts. However that is pretty slow in two ways. First QGIS needs always to handle the full control of the GRASS environment i.e. the grassbase, locations and mapset including knowledge of projection and so on. Secondly the calls have to send via the shell.

Due to this you will usually find about 6 commands around the one command of your desired operation. That really slows down the process. You can clean this up on commandline scripting but it is much more elegant and faster to tune into the GRASS python wrapper.

Actually you can start GRASS without an explicit GRASS session Please note - In this version you HAVE to create FIRST your correct mapsets and locations first. You will learn later how you can automate it.

Setting up GRASS
# Accessing GRASS modules without starting a GRASS session 
# we have to set first the necessary environ variable GISBASE and the Data directory for later use
# Take care the Location and Mapset MUST exist
# See http://grasswiki.osgeo.org/wiki/Working_with_GRASS_without_starting_it_explicitly#Python_example
 
location = 'tirol31254'
mapset   = 'alps'
rundir   = 'actualrun'
 
gisbase  = os.environ['GISBASE'] = '/usr/lib/grass64'
gisdbase = os.path.join(os.environ['HOME'], rundir)
sys.path.append(os.path.join(os.environ['GISBASE'], "etc", "python"))
# now we can load grass libs
import grass.script as g
import grass.script.setup as gsetup
 
# setup your working environment
gsetup.init(gisbase,gisdbase, location, mapset)
 
# look what you have done so far
print grass.gisenv()
python/howto/grass-setup.txt · Last modified: 2018/12/23 19:46 (external edit)