Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
import os
import tempfile
import shutil
import grass.script as grass
# first do:
# mkdir /tmp/grasstest
# wget
# unzip *.zip
GRASS_DB = '/tmp/grasstest/'
loc_name = 'nc_spm_08'
rast_name = 'elev_ned_30m'
def set_gisrc(grass_db, location, mapset):
fd, gisrc = tempfile.mkstemp()
os.write(fd, "GISDBASE: %s\n" % grass_db)
os.write(fd, "LOCATION_NAME: %s\n" % location)
os.write(fd, "MAPSET: %s\n" % mapset)
os.environ['GISRC'] = gisrc
return gisrc
def export(loc, name, out_fn='/tmp/exported.tif'):
gisrc = set_gisrc(GRASS_DB, loc, 'PERMANENT')
cmd = 'r.out.gdal'
kwargs = {
'quiet': True,
'flags': 'c',
'input': name,
'output': out_fn
process = grass.pipe_command(cmd, **kwargs)
stdout, stderr = process.communicate()
def run():
i = 0
while True:
i += 1
print 'Iteration %s' % i
work_dir = tempfile.mkdtemp()
out_fn = os.path.join(work_dir, 'rast.tif')
export(loc_name, rast_name, out_fn)
Copy link

wenzeslaus commented Jun 11, 2015

Since this can pop out in some search, it might be useful to note that unless you are switching Mapset (GISDBASE/LOCATION_NAME/MAPSET) there is no need for repetitive setting of GISRC variable and file. It this case the repetitive calls are just an overhead but in case of grass.script.init function it can lead to issues ( but it is important to note that using init function repetitively ( is a misuse of API and the question is what we are trying to achieve.

It might be also useful to mention that grass.script.pipe_commandfunction accepts Popen's env parameter ( which can be used to pass a custom environment to the subprocess without changing environment of the calling process or other called subprocesses. The code would be something like:

env = os.environ.copy()
env['GISRC'] = set_gisrc(...)
... = grass.pipe_command(cmd, env=env, **kwargs)

Just to follow what it in the sample code, I would suggest to use an object of a custom class to keep the environment in between calls of export which would be a method of this class.

The very recent development version of GRASS GIS also has improved grass.script.setup module with init and write_gisrc functions and documentation ( But again, it's important to know what is the goal. Perhaps even the latest addition to the grass command might be useful (,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment