python 函数调用 GRASS GIS 模块和另一个 python 同类函数时发生错误

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

我写了一个 python 函数 A 从外部调用 GRASSGIS 模块,运行 没问题。我写了另一个 python 函数 B 包含调用另一个 GRASSGIS 模块和 python 函数 A 的语句,发生错误。

函数 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

函数 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)

错误:

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

而且我已经测试了函数 B 没有语句调用函数 A 运行 没有错误。

我不知道为什么会这样,也不知道如何解决。

解决方法: 在顶级导入中有 from import grass.script as g 即文件 1 (function A - v_edit.py) 将是:

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

原因: 您在 if __name__ == "__main__" 块中定义(导入)了 g - 这不算作文件代码的一部分。

读这个 - what does if name == "main" do