【问题标题】:Error occurred when python function calling GRASS GIS module and another python function of the same kindpython函数调用GRASS GIS模块和另一个同类python函数时出错
【发布时间】:2016-10-26 13:19:13
【问题描述】:

我写了一个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

并且我已经测试了没有语句调用函数 A 的函数 B 运行良好,没有错误。

我不知道为什么会发生这种情况以及如何解决。

【问题讨论】:

    标签: python grass


    【解决方案1】:

    解决方案: 在顶级导入中包含来自 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

    【讨论】:

      猜你喜欢
      • 2023-02-08
      • 1970-01-01
      • 1970-01-01
      • 2014-04-06
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 1970-01-01
      • 2017-04-12
      相关资源
      最近更新 更多