操作方法

错误:通过 Python 调用模型或脚本工具时出现 AttributeError

Last Published: April 26, 2024

描述

通常会使用 ModelBuilder 来自动化耗时的流程。 该模型可能需要在下班后作为计划任务运行,为此需要一个 Python 脚本:

import arcpy
arcpy.ImportToolbox(r"path\to\toolbox.tbx")
arcpy.ModelName_ToolboxAlias()
通常,此操作执行不会出错。 但代码可能抛出 AttributeError 异常,例如:
'module' object has no attribute 'ModelName_ToolboxAlias'
Object: Tool or environment <> not found.
用户添加的图像

用户添加的图像

原因

由于以下原因之一,通过 Python 调用模型可能会引发 AttributeError:

  • 模型不存在
  • 模型名称拼写错误
  • Toolbox 别名拼写错误
  • 可能包含空格或下划线,或者
  • 模型是在 ArcGIS Pro 中创建的,并使用随 ArcGIS for Desktop 一起安装的 ArcPy 进行调用
要排查确切原因,请尝试:
import arcpy
arcpy.ImportToolbox(r"path\to\toolbox.tbx")
arcpy.ToolboxAlias.ModelName()
该错误略有不同,这有助于精确定位 Python 无法找到的对象。
  1. AttributeError:“module”对象没有属性“Model”
    这表示模型不存在,模型名称拼写错误,或者名称中可能包含空格或下划线。
  2. AttributeError:“module”对象没有属性“ToolboxAlias”
    这表示工具箱别名拼写错误,或者别名中可能包含空格或下划线。
Note:
Models that are newly created, as well as any models that have been edited and saved in ModelBuilder in ArcGIS Pro, cannot be used in other ArcGIS for Desktop applications. Therefore, attempts to call a model created in ArcGIS Pro with the ArcPy in Python 2.7, will raise an AttributeError. See: ModelBuilder: Migration to ArcGIS Pro

解决方案或解决方法

解决方案是:
  • 确保模型存在
  • 确保 Toolbox alias 和 Model name 拼写正确
  • 移除名称和别名中的空格或下划线
  • 使用 ArcGIS Pro 中安装的 Python 调用在 ArcGIS Pro 中创建的模型
例如,在工具箱属性对话框的别名中,删除下划线 ( _ )。

用户添加的图像 用户添加的图像

如有必要,也可以从模型或脚本工具的属性对话框中移除下划线 ( _ )。

用户添加的图像 用户添加的图像
移除工具箱别名和/或工具名称中的下划线 ( _ ) 后,该工具即可在 Python 窗口中使用。
用户添加的图像

文章 ID: 000014511

接收通知并查找新问题或常见问题的解决方案

从我们全新的 AI 聊天机器人中获得简明答案和视频解决方案。

下载 Esri 支持应用程序

相关信息

发现关于本主题的更多内容

获取来自 ArcGIS 专家的帮助

联系技术支持部门

下载 Esri 支持应用程序

转至下载选项