pythongrass

Error occurred when python function calling GRASS GIS module and another python function of the same kind


I wrote a python funciton A to call a GRASSGIS module from outside, and it ran fine. I wrote another python function B containing statement calling another GRASSGIS module and python function A, error occurred.

function A:

import os
import sys
import numpy
from GRASSGIS_conn import GRASSGIS_conn


def v_edit(map_name, tool, thresh, coords):

    cor = [",".join(item) for item in coords.astype(str)]
    no_of_cors = len(cor)
    i = 0
    while i <= no_of_cors - 1:
        g.run_command('v.edit', map = map_name, tool = tool, threshold = thresh, coords = cor[i])
        i = i + 1

function B:

import sys
import os
import numpy
from GRASSGIS_conn import GRASSGIS_conn
from v_edit import v_edit


def split_line(line_shape, out_name, thresh, point_cor):

    g.run_command('v.in.ogr', overwrite = True, input = line_shape, output = out_name)
    v_edit(out_name, 'break', thresh, point_cor)



if __name__ == "__main__":


    sys.path.append(os.path.join(os.environ['GISBASE'], 'etc', 'python'))
    import grass.script as g
    gisdb = 'C:\Users\Heinz\Documents\grassdata'
    location = 'nl'
    mapset = 'nl'
    GRASSGIS_conn(gisdb, location, mapset)
    point_cor = numpy.genfromtxt('proj_cor.csv', delimiter = ',')
    split_line(r'C:\Users\Heinz\Desktop\all.shp', 'tctest', '50', point_cor)

error:

Traceback (most recent call last):
  File "C:\Users\Heinz\Desktop\split_line.py", line 25, in <module>
    split_line(r'C:\Users\Heinz\Desktop\all.shp', 'tctest', '50', point_cor)
  File "C:\Users\Heinz\Desktop\split_line.py", line 11, in split_line
    v_edit(out_name, 'break', thresh, point_cor)
  File "C:\Users\Heinz\Desktop\v_edit.py", line 13, in v_edit
    g.run_command('v.edit', map = map_name, tool = tool, threshold = thresh, coords = cor[i])
NameError: global name 'g' is not defined

And I have tested that function B without the statement calling function A ran well without error.

I don't know why this happened and how to solve it.


Solution

  • Solution: Have the from import grass.script as g in the top level imports i.e. file 1 (function A - v_edit.py) will be:

    import os
    import sys
    import numpy
    from GRASSGIS_conn import GRASSGIS_conn
    import grass.script as g
    
    def v_edit(map_name, tool, thresh, coords):
    
        cor = [",".join(item) for item in coords.astype(str)]
        no_of_cors = len(cor)
        i = 0
        while i <= no_of_cors - 1:
            g.run_command('v.edit', map = map_name, tool = tool, threshold = thresh, coords = cor[i])
            i = i + 1
    

    Cause: You have g defined (imported) in if __name__ == "__main__" block - which doesn't count as part of file code.

    Read this - what does if name == "main" do.