杰瑞科技汇

ArcGIS Object Python如何入门?

Of course! This is a fantastic topic. Working with ArcGIS objects in Python is the core of what makes ArcPy so powerful. It allows you to move beyond simple, script-by-script execution and interact with ArcGIS Pro or ArcMap as if you were a developer building a custom application.

ArcGIS Object Python如何入门?-图1
(图片来源网络,侵删)

Let's break this down into key concepts, with clear examples.

What is an ArcGIS Object?

In the context of ArcGIS, an "object" is any item you see and interact with in the ArcGIS Pro or ArcMap interface. These are not just simple variables; they are complex entities with properties (attributes) and methods (actions they can perform).

  • Examples of ArcGIS Objects:
    • A map (has properties like name, extent, and layers; has methods like addLayer()).
    • A layer (has properties like dataSource, visible, name; has methods like zoomTo()).
    • A table (has properties like name, fields; has methods like search()).
    • A geoprocessing tool (is itself an object you can call).
    • An arcpy module object, like arcpy.env.workspace (which is a Workspace object).

The key is that you can get a reference to one of these objects and then control it directly from your Python script.


The Two Main Ways to Work with ArcGIS Objects in Python

There are two primary methods, depending on whether you're using ArcGIS Pro or ArcMap.

ArcGIS Object Python如何入门?-图2
(图片来源网络,侵删)

The ArcPy Approach (ArcGIS Pro & ArcMap)

This is the most common and recommended method. You use the arcpy module, which is Python's bridge to the ArcGIS geoprocessing engine. You don't typically create these objects from scratch (my_map = Map()). Instead, you get a reference to an existing object.

How to Get a Reference to an Object:

  • From a Geoprocessing Tool Result: Many tools return an object.
  • From a Path: Use functions like arcpy.mp.ArcGISProject() or arcpy.mapping.Layer().
  • From the Current Application: Use arcpy.mp.ArcGISProject("CURRENT") to get a reference to the project you currently have open in ArcGIS Pro.

The ArcGIS API for Python Approach (ArcGIS Pro & ArcGIS Online/Enterprise)

This is a more modern, object-oriented approach, especially powerful for working with ArcGIS Online and ArcGIS Enterprise (Portal for ArcGIS). It uses the arcgis library, which you install separately (pip install arcgis).

This API is designed for automation, content management, and analysis across the entire ArcGIS platform, not just local data. It's a different library from arcpy but serves a similar purpose of controlling ArcGIS objects.

ArcGIS Object Python如何入门?-图3
(图片来源网络,侵删)

Detailed Examples

Let's focus on the most common and powerful approach: ArcPy with ArcGIS Pro (arcpy.mp).

Example 1: Working with the ArcGIS Project (arcpy.mp.ArcGISProject)

The ArcGIS Project (.aprx) is the main container in ArcGIS Pro. It's the top-level object.

import arcpy
import os
# --- Setup ---
# Set the current workspace to the project's folder
# This makes it easier to manage paths
project_path = r"C:\Data\MyAwesomeProject\MyAwesomeProject.aprx"
arcpy.env.workspace = os.path.dirname(project_path)
# --- Get a Reference to the Project ---
# This is the key step. We are not creating a new project, we are getting a reference to an existing one.
aprx = arcpy.mp.ArcGISProject(project_path)
# --- Explore the Project's Properties and Methods ---
print(f"Project Name: {aprx.name}")
print(f"Project Description: {aprx.description}")
print("-" * 30)
# --- Get a Reference to a Map Object ---
# A project can have multiple maps. Let's get the first one.
# The result is a Map object.
map_obj = aprx.listMaps()[0] 
print(f"Map Name: {map_obj.name}")
print(f"Map's Data Frame: {map_obj.dataFrame}")
print(f"Map's Scale: {map_obj.scale}")
print("-" * 30)
# --- Interact with the Map Object (Call a Method) ---
# Let's add a new layer to the map
# We need a valid layer file path first
new_layer_path = r"C:\Data\Boundaries\City_Limits.lyr"
if os.path.exists(new_layer_path):
    # Use the addLayer() method of the Map object
    map_obj.addLayer(new_layer_path, "TOP")
    print(f"Successfully added layer '{os.path.basename(new_layer_path)}' to map '{map_obj.name}'")
    # --- Save the changes to the project ---
    aprx.save()
    print("Project changes saved.")
else:
    print(f"Error: Layer file not found at {new_layer_path}")
# --- Clean up ---
# It's good practice to release the object reference
del aprx

Example 2: Working with a Layer Object

Now let's get a reference to a specific layer and inspect its properties.

import arcpy
# --- Setup ---
# Use "CURRENT" to get a reference to the project open in ArcGIS Pro
aprx = arcpy.mp.ArcGISProject("CURRENT")
map_obj = aprx.listMaps("Map")[0] # Get the map named "Map"
# --- Get a Reference to a Layer Object ---
# Let's get the first layer in the map
layer_obj = map_obj.listLayers()[0]
print(f"Layer Name: {layer_obj.name}")
print(f"Layer is Visible: {layer_obj.visible}")
print(f"Layer's Data Source: {layer_obj.dataSource}")
print("-" * 30)
# --- Inspect the Layer's Fields (a property of the Layer object) ---
print("Fields in the layer:")
for field in layer_obj.fields:
    print(f"- {field.name} (Type: {field.type})")
print("-" * 30)
# --- Interact with the Layer Object (Call a method) ---
# Let's turn the layer off and then zoom to its features
print("Turning layer off...")
layer_obj.visible = False # This is a property, not a method
print("Zooming to layer...")
# The zoomToFeatures() method requires a list of layers
map_obj.zoomToFeatures([layer_obj])
# --- Save and Clean up ---
aprx.save()
del layer_obj, map_obj, aprx
print("Script finished.")

Example 3: Working with a Table Object

This is very similar to working with a layer.

import arcpy
# --- Setup ---
aprx = arcpy.mp.ArcGISProject("CURRENT")
map_obj = aprx.listMaps()[0]
# --- Get a Reference to a Table Object ---
# Note: listTables() is a method of the Map object
table_obj = map_obj.listTables()[0]
print(f"Table Name: {table_obj.name}")
print(f"Table's Data Source: {table_obj.dataSource}")
print("-" * 30)
# --- Get a Row Count (a property) ---
# This is much faster than arcpy.GetCount_management for some data sources
print(f"Number of rows in table: {table_obj.rowCount}")
print("-" * 30)
# --- Read Data from the Table ---
print("First 5 rows from the table:")
# A SearchCursor is the standard way to iterate through rows
# The table object is passed as the first argument
with arcpy.da.SearchCursor(table_obj, ["*"]) as cursor: # "*" gets all fields
    row_count = 0
    for row in cursor:
        print(row)
        row_count += 1
        if row_count >= 5:
            break
# --- Clean up ---
del table_obj, map_obj, aprx

Key Differences: ArcPy vs. ArcGIS API for Python

Feature arcpy (ArcPy) arcgis (ArcGIS API for Python)
Primary Focus Geoprocessing & Desktop (ArcGIS Pro, ArcMap, ArcGIS Server). Manages data, maps, and analysis on local machines or a server. Content & Platform (ArcGIS Online, ArcGIS Enterprise). Manages users, groups, content (items), portals, and data in the cloud.
Installation Comes with ArcGIS Pro/ArcMap. No pip install needed. Requires pip install arcgis.
Object Model arcpy.mp for maps/projects, arcpy.mapping (older), arcpy tools for data manipulation. arcgis.gis for portal content, arcgis.mapping for web maps, arcgis.features for feature layers.
Example Use Automate creating a map series, update layer symbology in a dozen .aprx files, run complex spatial analysis. Publish a service to ArcGIS Enterprise, create a group and add users, search for content in your organization.

Summary and Best Practices

  1. Start with arcpy.mp for Desktop Automation: If your goal is to automate tasks within ArcGIS Pro (
分享:
扫描分享到社交APP
上一篇
下一篇