[GIS] How to use GRASS GIS in Python standalone

grasspython

I'm trying to use GRASS module in a Python Skript. I already checked this:
Is it possible to use GRASS GIS in Python stand alone scripts?
and this Using Python script to control GRASS GIS from outside?
but it doesn't help with my problem.
I did pip install grass-session which worked well. My script is just:
import grass_session and when I run it I get the error RuntimeError: Cannot find GRASS GIS start script: 'grass', set the right one using the GRASSBIN environm. variable.

First I tried GRASSBIN="$path\\to\\software\\grass\\grass78 python grass.py" as suggested in
https://grasswiki.osgeo.org/wiki/Working_with_GRASS_without_starting_it_explicitly in the block Python: GRASS GIS 7 with an external library: grass-session but I still got the same error.

After checking http://osgeo-org.1560.x6.nabble.com/GRASSBIN-environment-variable-td5413301.html I solved this error adding the following line before the import line: os.environ['GRASSBIN']=r"path\to\software\grass\grass78", although I feel this only should be necessary if my grass version is different from 7.8.

Now when I run these two lines first I'm happy to see that I don't get the error again but after a while I notice that nothing happens. It keeps running without any exit code unless I stop the script manually. I would expect the script to import the module and finish with exit code 0.

I have grass gis 7.8.2. installed with QGIS and Python 3.7 and working on Windows 10 Pro 64 bit.

Best Answer

If you have already started GRASS interactively, and created a LOCATION/MAPSET, then try the full code example:from the wiki.

If you do not yet have your GRASS DB setup, and you want to try constructing a temporary location using python, then the next wiki section gives a working example.

Please try those complete examples, then post back if something does not work.

Edited:

You should not have to do any pip install grass. In the setup script are the lines:

# Set GISBASE environment variable
os.environ['GISBASE'] = gisbase
# define GRASS-Python environment
gpydir = os.path.join(gisbase, "etc", "python")
sys.path.append(gpydir)

If you have GRASS installed, that should take care of finding the GRASS python module grass.script. Can you double check that you are getting the paths correct, etc.??

Related Question