[GRASS-user] Envoking GRASS in a python script
Glynn Clements
glynn at gclements.plus.com
Tue Oct 18 07:44:20 EDT 2011
kungphil wrote:
> I am trying to envoke GRASS 6.4.1 from a python(2.6) script on a Solaris 10
> OS, I am creating the WIND, PROJ_INFO and PROJ_UNITS from a PSQL database
> table and this seems to work fine as it creates a vaible GRASS session. The
> next seesion is the part I am havin a problem with, please see script
> below...
>
> Import os, sys, psycopg2, getpass, shutil, shlex
>
> user = getpass.getuser()
>
> #Create temporary GRASS directories
> tLOCATION = ('/home/syst/' + user + '/tempGRASS')
Use os.path.join() for constructing paths. Also, os.path.expanduser()
for locating a user's home directory.
> #GRASS environment variables
> os.environ['PYTHONPATH'] = '$PYTHONPATH:/opt/isg/grass-6.4.1-64/etc/python'
> os.environ['GISBASE'] = '/opt/isg/grass-6.4.1-64'
> os.environ['PATH'] = '$PATH:$GISBASE/bin:$GISBASE/scripts'
> os.environ['LD_LIBRARY_PATH'] = '$LD_LIBRARY_PATH:$GISBASE/lib'
> os.environ['GIS_LOCK'] = '$$'
> os.environ['GISRC'] = tLOCATION + '/PERMANENT/GRASSRC'
This is trying to use Bourne-shell syntax, where "$var" is replaced by
the value of the environment variable "var"; this won't work in
Python. Instead, you need e.g.:
gisbase = '/opt/isg/grass-6.4.1-64'
bindir = os.path.join(gisbase, 'bin')
scriptdir = os.path.join(gisbase, 'scripts')
pythondir = os.path.join(gisbase, 'etc', 'python')
libdir = os.path.join(gisbase, 'lib')
os.environ['GISBASE'] = gisbase
os.environ['PATH'] = os.pathsep.join(os.environ['PATH'],bindir,scriptdir)
os.environ['PYTHONPATH'] = os.pathsep.join(os.environ['PYTHONPATH'],pythondir)
os.environ['LD_LIBRARY_PATH'] = os.pathsep.join(os.environ['LD_LIBRARY_PATH'],libdir)
For GIS_LOCK:
os.environ['GIS_LOCK'] = str(os.getpid())
> Doing this I get an error (with traceback)...
> File "/opt/isg/lib/python2.6/subprocess.py", line 1126, in _execute_child
> raise child_exception
> OSError: [Errno 2] No such file or directory
This is because PATH isn't set correctly.
> As an aside I don't think the os.environ is working correctly, if I comment
> out the 'import grass.script as grass' and below and then run the script I
> get no error (then get the error above if I include it again), but if I run
> the above script in a new shell I get the error...
>
> No module named grass.script
This is because PYTHONPATH isn't set correctly.
--
Glynn Clements <glynn at gclements.plus.com>
More information about the grass-user
mailing list