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

标签 python grass

我编写了一个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 importgras.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__" block 中定义(导入)了 g - 它不算作文件代码的一部分。

阅读此内容 - what does if name == "main" do .

关于python - python函数调用GRASS GIS模块和另一个同类python函数时发生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40263422/

相关文章:

python - 使用 python PRAW 提取 reddit 评论并使用结果创建数据框

python - 如何在 Python 中将单个函数导出为模块?

python - 从 cron 表达式创建 apscheduler 作业触发器

python - 使用 GeoPandas 在 Python 中读取 GRASS 矢量数据源

python - 如何使用 Python 2.4 解压缩文件?

python - 如何在终端中执行 "python"命令,运行 python3 而不是 python2?

rpm - "Missing"用于 rpm 安装的 lib(当它存在于 rpm 文件中时)

Rmarkdown 无法正确重现 bash 代码

从草地 gis 导出多个栅格