共享 Python 脚本的技术
ArcGIS 10以下将介绍一些您在与其他用户共享 Python 脚本时可使用的技术。
相对脚本位置查找数据
对于不以参数形式传递的现有数据,您的脚本可能需要使用其路径(程序员称之为硬连接路径)。例如,您可能需要将输出参数的符号系统属性设置为某个现有图层文件,或者需要将数据裁剪为某个已知数据集。
与其他用户共享工具时,您需要确保脚本能够找到其所需数据。为此,建议您使用 ToolShare 文件夹结构。您可以将工程数据和脚本分别放在 ToolData 和 Scripts 文件夹中。如果采用此方式,您始终可以相对于脚本位置找到数据。
当运行脚本时,可按照以下方法查找该脚本的路径:
scriptPath = sys.path[0]
已知该位置后,您可以找到此位置对应的工程数据。以下代码片段演示了这个示例:
import arcpy import os import sys # Get the pathname to this script # scriptPath = sys.path[0] arcpy.AddMessage("Script folder: " + scriptPath) # Get the pathname to the ToolShare folder # toolSharePath = os.path.dirname(scriptPath) arcpy.AddMessage("ToolShare folder: " + toolSharePath) # Now construct pathname to the ToolData folder # toolDataPath = os.path.join(toolSharePath, "ToolData") arcpy.AddMessage("ToolData folder: " + toolDataPath) # Create the pathname to the parks feature class found in the ToolData folder # parkPath = os.path.join(toolDataPath, "Project.gdb/Parks") arcpy.AddMessage("Parks feature class: " + parkPath)
如果嵌入脚本代码,则 sys.path[0] 将返回工具箱的位置(即代码所在的位置)。
查找临时工作空间
如果要在脚本中创建临时数据,则需要一个临时工作空间用于创建和后续删除临时数据。
以下是有关查找临时工作空间的注意事项:
- 您需要具有此工作空间的写入权限。
- 如果设置了临时工作空间地理处理环境,则使用此环境,必须假定用户已特意将其设置为可写入的位置。对于在 ArcGIS 服务器上运行的地理处理服务,ArcGIS Server 会自动将临时工作空间设置为可写入的特定文件夹。