From c55ad9256db8cff88918a44fee3e04bb335c2ef4 Mon Sep 17 00:00:00 2001
From: Julien Veyssier <eneiluj@posteo.net>
Date: Sat, 18 Apr 2020 02:47:18 +0200
Subject: [PATCH] make grass.script accessible in qgis python => OK

Signed-off-by: Julien Veyssier <eneiluj@posteo.net>
---
 hrudelin_dockwidget.py | 24 +++++++++++++++++++++-
 pluginUtils/tools.py   | 46 +++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 68 insertions(+), 2 deletions(-)

diff --git a/hrudelin_dockwidget.py b/hrudelin_dockwidget.py
index b354cf3..bc9d1b5 100644
--- a/hrudelin_dockwidget.py
+++ b/hrudelin_dockwidget.py
@@ -47,7 +47,7 @@ from qgis._gui import *
 import processing
 
 from hrudelin.pluginUtils import layerstools
-from hrudelin.pluginUtils.tools import isWindows, isMac, which
+from hrudelin.pluginUtils.tools import isWindows, isMac, which, prepareGrassEnv
 
 # this exception is used by the QgisTasks
 class CancelException(Exception):
@@ -64,6 +64,7 @@ class HruDelinDockWidget(QtWidgets.QDockWidget, FORM_CLASS):
     def __init__(self, parent, iface):
         """Constructor."""
         super(HruDelinDockWidget, self).__init__(parent)
+        prepareGrassEnv()
         # Qgis interface, used to get main window, manipulate messageBar etc...
         self.iface = iface
         # can be set within the interface
@@ -876,9 +877,30 @@ class HruDelinDockWidget(QtWidgets.QDockWidget, FORM_CLASS):
     def processStep1(self, task):
         task.setProgress(0)
 
+        # TODO move environment building from bash to hrudelin core
+        # TODO adapt hrudelin core to be executed AND to be imported as a module
         #HruDelinCore.step1(self.configFilePath)
         print('inside STEP 1 task')
 
+        #os.environ['GISRC'] = '/home/julien/data/j2k_test/grass_db/grassdata/hru-delin/.grassrc'
+        #import grass.script as grass
+        #print('--- GISBASE')
+        #print(os.environ['GISBASE'])
+        #print('--- PATH')
+        #print(os.environ['PATH'])
+        #print('--- LD_LIB')
+        #print(os.environ['LD_LIBRARY_PATH'])
+
+        #grass.run_command('r.mapcalc', expression='toto=22', overwrite=True)
+        ##import subprocess
+        ##subp = subprocess.check_output(['r.info', 'map=toto'])
+        ##print('SUBP %s' % subp)
+        #res = grass.read_command('r.info',
+        #    #quiet=True, flags='nNc',
+        #    map='toto')
+        ##.decode('utf-8')
+        #print('RESSS %s' % res)
+
         return True
 
     def processStep2(self, task):
diff --git a/pluginUtils/tools.py b/pluginUtils/tools.py
index f7ec096..b6f9bef 100644
--- a/pluginUtils/tools.py
+++ b/pluginUtils/tools.py
@@ -1,5 +1,6 @@
 import platform
-import os
+import os, sys
+from pathlib import Path
 
 def isWindows():
     plat = platform.system()
@@ -31,3 +32,46 @@ def split_list(alist, wanted_parts=1):
     return [ alist[i*length // wanted_parts: (i+1)*length // wanted_parts]
              for i in range(wanted_parts) ]
 
+def prepareGrassEnv():
+    # sys.path (to be able to import grass.script)
+    # find grass depending on the system
+    if isWindows():
+        pass
+    elif isMac():
+        pass
+    else:
+        for grassVersion in ['74', '75', '76', '77', '78', '79']:
+            findRes = list(Path('/usr/lib/grass%s' % grassVersion).rglob('*r.thin*'))
+            if len(findRes) > 0:
+                thinPath = str(findRes[0])
+                grassBasePath = os.path.dirname(os.path.dirname(thinPath))
+                grassPythonPath = os.path.join(grassBasePath, 'etc', 'python')
+                if grassPythonPath not in sys.path:
+                    sys.path.append(grassPythonPath)
+                break
+        os.environ['GISBASE'] = grassBasePath
+
+        libPathToAdd = os.path.join(grassBasePath, 'lib')
+        existingLdLibraryPath = ''
+        if 'LD_LIBRARY_PATH' in os.environ:
+            existingLdLibraryPath = os.environ['LD_LIBRARY_PATH']
+        if libPathToAdd not in existingLdLibraryPath.split(':'):
+            os.environ['LD_LIBRARY_PATH'] = '%s:%s' % (existingLdLibraryPath, libPathToAdd)
+
+        pyPathToAdd = os.path.join(grassBasePath, 'etc', 'python')
+        existingPYTHONPATH = ''
+        if 'PYTHONPATH' in os.environ:
+            existingPYTHONPATH = os.environ['PYTHONPATH']
+        if pyPathToAdd not in existingPYTHONPATH.split(':'):
+            os.environ['PYTHONPATH'] = '%s:%s' % (existingPYTHONPATH, pyPathToAdd)
+
+        grassBinPath = os.path.join(grassBasePath, 'bin')
+        grassScriptPath = os.path.join(grassBasePath, 'scripts')
+        existingPath = ''
+        if 'PATH' in os.environ:
+            existingPath = os.environ['PATH']
+        if grassBinPath not in existingPath.split(':'):
+            os.environ['PATH'] = '%s:%s' % (existingPath, grassBinPath)
+            existingPath = os.environ['PATH']
+        if grassScriptPath not in existingPath.split(':'):
+            os.environ['PATH'] = '%s:%s' % (existingPath, grassScriptPath)
\ No newline at end of file
-- 
GitLab