### Sidebar

#### Applied Stuff

2019/08/15 10:57 ·
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.

# 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