[GRASS-user] syntax for setting GRASS_PNGFILE from Python script

Glynn Clements glynn at gclements.plus.com
Wed Sep 1 14:01:20 EDT 2010


Martin Landa wrote:

> > GRASS_PNGFILE=mywaycoolmap.png
> > export GRASS_PNGFILE
> >
> > What is the proper syntax for setting this in Python?
> >
> > I have tried something like:
> >
> > def jpgMap():
> >    #SET PNG OUTPUT FILE NAME
> >    grass.run_command("g.gisenv", set="GRASS_PNGFILE=testName.png")
> 
> GRASS_PNGFILE is a shell environment variable, not a GRASS gisenv
> variable [1]. To set environment variable use e.g. os.putenv()
> 
> os.putenv('GRASS_PNGFILE', 'test.png')

If you want to set an environment variable for the duration of a
script, the preferred mechanism is to modify the os.environ array,
i.e.:
	os.environ['GRASS_PNGFILE'] = 'test.png'

Modifying os.environ will call os.putenv() if it is available (it
doesn't exist on all platforms supported by Python), but calling
os.putenv() doesn't modify os.environ, so calling os.putenv() will
result in os.environ and the actual environment used by subprocesses
getting out of sync.

If you want to set an environment variable for specific commands, use
the "env" parameter to run_command() etc to pass an updated
environment, e.g.:

	environ = os.environ.copy()
	environ['GRASS_PNGFILE'] = 'test.png'

	grass.run_command(..., env = environ)

This approach should be used if you will be running different commands
with different environment settings. Changing os.environ then
reverting it after the command completes is error-prone and should not
be used. Only modify os.environ if the changes will be "permanent"
(i.e. for the duration of the script).

-- 
Glynn Clements <glynn at gclements.plus.com>


More information about the grass-user mailing list