ArcGISProject

摘要

ArcGISProject 对象用于访问 ArcGIS Pro 工程方法和属性。 大多数地图自动化工作流都需要引用此对象。

说明

ArcGISProject 对象通常是最先引用的对象之一(这些引用是在地图自动化脚本中创建的),因为它是用于访问 ArcGIS Pro 中大多数其他对象的主要入口点。 可使用 ArcGISProject 函数引用工程。 其属性可用于获取或设置以下工程设置:defaultGeodatabasedefaultToolboxdocumentVersionfilePath 等。 其方法(例如 updateFolderConnectionsupdateDatabasescreateMapcreateLayout)可用于管理工程项目,用户也可以使用 copyItemdeleteItem 方法相应地复制或删除某些工程项目。

updateConnectionProperties 方法可用于替换工程中的数据源。 可以在 ArcGISProjectMapLayerTable 对象上替换数据源。 有关更多详细信息和代码示例,请参阅更新和修复数据源

importDocument 方法允许您将地图文档 (.mxd)、globe 文档 (.3dd) 和 scene 文档 (.sxd) 导入到工程中。 此操作提供了用于将这些文档类型自动转换为 ArcGIS Pro 工程的机制。 importDocument 方法还允许您将地图文件 (.mapx)、布局文件 (.pagx) 和报表文件 (.rptx) 导入到现有工程中。

具有对 ArcGISProject 对象的引用后,您可以使用多个列表函数访问其他对象。 例如,您可以使用 listMaps 方法访问 Map 对象,或分别使用 listLayoutslistReports 方法访问 LayoutReport 对象。

下图沿左侧演示了使用列表函数导航和引用工程中对象的方法。 该图仅为示例,不显示完整对象集合和列表方法。

演示列表和创建函数使用方法的 ArcGISProject 对象模型示意图示例。

上方右侧示意图还演示了许多创建函数。 例如,您可以使用 createMap 创建 Map 对象,或使用 createLayout 创建 Layout 对象。

注:

createGraphicElementcreateGroupElementcreatePictureElementcreateTextElement 方法也可用于 ArcGISProject 对象,因为通过这些方法可以在 Layout 对象中创建元素,或在 Map 对象中创建图形图层。

提示:

在地图中的图形图层中创建元素时,图形图层的要素数量和整体大小均受到限制。 有关详细信息,请参阅使用图形图层

有几个方法和属性仅适用于在应用程序内部运行的脚本,例如在 Python 窗口或笔记本中运行的脚本或与脚本工具关联的脚本。 它们是 activeMapactiveView 属性以及 closeViews() 方法。 activeMap 属性将返回与活动布局视图上的活动地图视图或活动地图框关联的 Map 对象。 如果不满足上述条件,则将返回 NoneType。 如果地图视图为活动状态,activeView 属性将返回 MapView 对象,如果布局视图处于活动状态,则会返回 Layout 对象。 如果没有活动视图,则两种属性都将返回 None。 当脚本在应用程序外部运行时,这些属性将始终返回 None 值,因为视图仅在应用程序打开时才会相关。 从 activeView 属性返回的 MapView 对象是更改与地图视图相关联的范围的唯一方法。 MapView 类提供多个可用于更改范围的函数,例如 camerapanToExtentZoomToAllLayersZoomToBookmarkscloseViews 函数可用于关闭应用程序内的特定视图类型。 要关注特定视图,请关闭所有视图并在 LayoutMapReport 类上使用 openView 方法。

注:

工程可以被多次引用,但是仅第一次引用可以直接保存,因为其他引用将以只读模式打开。 ArcGISProject 对象具有一个 isReadOnly 属性,该属性可用于在调用方法(例如 saveACopy 方法,而非 save)之前确定工程的读取状态。

属性

属性说明数据类型
activeMap
(只读)

返回与应用程序内部焦点视图相关联的地图对象。 如果布局视图处于活动状态,则其将返回与活动地图框相关联的地图

注:

该属性设计为在应用程序内通过脚本工具、Python 窗口或笔记本运行。 如果脚本在应用程序外部运行,则将始终返回值 None

Map
activeView
(只读)

将返回 MapViewLayout,具体取决于当前视图。 如果 ArcGIS Pro 工程未打开视图,或者活动视图为地图视图或布局视图之外的其他内容(例如,图表、表格、Model Builder 视图等),则将返回 None

注:

该属性设计为在应用程序内通过脚本工具、Python 窗口或笔记本运行。 如果脚本在应用程序外部运行,则将始终返回值 None

Object
databases
(只读)

返回 Python 字典列表,每个字典表示工程中各个数据库的属性。 要修改数据库,请参阅 updateDatabases 方法。

List
dateSaved
(只读)

返回报告上次工程保存日期的 Python datetime 对象。

DateTime
defaultGeodatabase
(可读写)

工程的默认地理数据库位置。 字符串必须包含地理数据库的完整路径和文件名。

注:

此属性可由系统管理员通过应用程序设置进行锁定。

String
defaultToolbox
(可读写)

工程的默认工具箱位置。 字符串必须包含工具箱的完整路径和文件名。

注:

此属性可由系统管理员通过应用程序设置进行锁定。

String
documentVersion
(只读)

根据上次保存文档的时间返回文档版本。 运行 savesaveACopy 将更新文档版本,以匹配应用程序版本。

String
filePath
(只读)

返回报告完全限定的工程路径和文件名的字符串值。

String
folderConnections
(只读)

返回 Python 字典列表,每个字典表示工程中各个文件夹连接的属性。 要修改文件夹连接,请参阅 updateFolderConnections 方法。

List
homeFolder
(可读写)

工程的主目录文件夹位置。 字符串必须包含所需位置的完整路径。

注:

此属性可由系统管理员通过应用程序设置进行锁定。

String
isReadOnly
(只读)

如果工程已在应用程序的另一个实例中打开或由另一个脚本参考,返回 True。 已知当前状态可确定您是否可以save工程或是否需要调用 saveACopy 等。

Boolean
metadata
(可读写)

获取或设置工程的元数据类信息。 注:设置元数据取决于 isReadOnly 属性值。

Metadata

方法概述

方法说明
closeViews ({view_type})

用于关闭当前在 ArcGIS Pro 中打开的视图窗格。

copyItem (project_item, {new_name})

创建现有 layoutmapreport 工程项目的副本。

createGraphicElement (container, geometry, {style_item}, {name}, {lock_aspect_ratio})

createGraphicElement 方法用于在指定 container 中创建 GraphicElement

createGroupElement (container, element_list, {name})

createGroupElement 方法用于在指定 container 中创建 GroupElement

createLayout (page_width, page_height, page_units, {name})

createLayout 方法将创建 Layout,其将自动添加至目录窗格。

createMap ({name}, {map_type})

此方法会创建一个地图,以自动添加至目录窗格。

createPictureElement (container, geometry, path, {name}, {lock_aspect_ratio})

createPictureElement 方法用于在指定 container 中创建 PictureElement

createPredefinedGraphicElement (container, geometry, shape_type, {style_item}, {name}, {lock_aspect_ratio})

createPredefinedGraphicElement 方法用于在指定 container 中创建 GraphicElement

createTextElement (container, geometry, text_type, text, {text_size}, {font_family_name}, {font_style_name}, {style_item}, {name}, {lock_aspect_ratio})

createTextElement 方法用于在指定 container 中创建 TextElement 对象。

deleteItem (project_item)

删除布局地图报表工程项目。

importDocument (document_path, {include_layout}, {reuse_existing_maps})

将地图文档 (.mxd)、globe 文档 (.3dd) 和场景文档 (.sxd) 导入到 ArcGIS Pro 工程中。 还可以用于导入地图文件 (.mapx)、布局文件 (.pagx) 和报表文件 (.rptx) 的内容。

listBasemaps ({wildcard})

listBasemaps 方法将引用工程中的可用底图。

listBrokenDataSources ()

返回项目中到所有地图原始源数据的连接存在断开情况的 Layer 和/或 Table 对象的 Python 列表。

listColorRamps ({wildcard})

listColorRamps 方法将引用工程中的可用色带。

listLayouts ({wildcard})

返回 ArcGIS 工程 (.aprx) 中的 Layout 对象的 Python 列表。

listMaps ({wildcard})

返回 ArcGIS 工程 (.aprx) 中的 Map 对象的 Python 列表。

listReports ({wildcard})

返回 ArcGIS 工程 (.aprx) 中的报表对象的 Python 列表。

listStyleItems (style, style_class, {wildcard})

listStyleItems 方法引用工程中可用的系统、个人和自定义样式。

save ()

将更改保存至 ArcGISProject (.aprx)。

saveACopy (file_name)

ArcGISProject (.aprx) 保存到新文件路径或另存为新文件名。

updateConnectionProperties (current_connection_info, new_connection_info, {auto_update_joins_and_relates}, {validate}, {ignore_case})

updateConnectionProperties 方法使用工作空间字典或路径替换连接属性。

updateDatabases (databases, {validate})

updateDatabases 方法将使用描述每个数据库的字典列表替换工程数据库。

updateFolderConnections (folder_connections, {validate})

updateFolderConnections 方法将使用描述每个连接的字典列表替换工程文件夹连接。

方法

closeViews ({view_type})
参数说明数据类型
view_type

A constant that determines the type of views to be closed in the application.

  • LAYOUTSClose all open layout view panes.
  • MAPSClose all open map view panes.
  • MAPS_AND_LAYOUTSClose all open layout and map view panes.
  • REPORTSClose all open report view panes.

(默认值为 MAPS_AND_LAYOUTS)

String

有时,在打开特定视图之前,需要清理应用程序中许多打开的视图以更好地查看结果视图时,此方法将非常有用。 该方法仅限于关闭与布局地图报表相关联的视图窗格。 此方法还将关闭与 "MAP" 相关联的表视图。

注:

此方法旨在使用脚本工具、Notebook 或 Python 窗口在应用程序内运行。 如果在应用程序之外执行该方法,则其将无效。

copyItem (project_item, {new_name})
参数说明数据类型
project_item

An object reference that represents a supported project item to be copied.

Object
new_name

An optional string that represents the name of the new project item. If a name is not provided, the default name will follow the sequencing nomenclature, for example, Map, Map1, Map2.

String
返回值
数据类型说明
Object

如果指定了变量参考,返回的对象将表示布局地图报表工程项目。

如果您想要修改现有工程项目的副本,而不对原始项目进行更改,建议使用此方法。 可以复制布局地图报表工程项目。

createGraphicElement (container, geometry, {style_item}, {name}, {lock_aspect_ratio})
参数说明数据类型
container

A reference to a Layout object, a graphics layer in a Map object, or a GroupElement object in a layout or a graphics layer.

Object
geometry

The appropriate Point, Polyline, or Polygon object that will be used to construct the graphic element. Page units should be used for layouts and map units should be used for elements in a graphics layer.

Object
style_item

An optional reference to a StyleItem. The style's intended geometry must match the geometry input parameter. If a style_item value is not specified, a default style item will be applied.

String
name

An optional string that represents the name of the new GraphicElement. If a name is not provided, the default name value will follow the automatic sequencing nomenclature, for example, Point, Point 1, Point 2, and so on.

String
lock_aspect_ratio

An optional Boolean that controls how the element can be resized. For example, if the value is True, setting the elementHeight value will also set the elementWidth value proportionally.

(默认值为 True)

Boolean
返回值
数据类型说明
GraphicElement

如果提供了变量,则其将引用新返回的 GraphicElement 对象。

此方法位于 ArcGISProject 对象上,因为 container 属性允许您在 Layout 对象、Map 对象的图形图层或者布局或图形图层的 GroupElement 对象中创建图形元素。

如果元素使用点几何进行创建,则点位置将代表 anchor 位置,并且存在默认大小。 稍后,可以使用 elementWidthelementHeight 属性调整元素的大小。 createPredefinedGraphicElement 方法非常类似,但是它允许创建常用的预定义形状。

有关详细信息和代码示例,请参阅 GraphicElement 类帮助主题。

createGroupElement (container, element_list, {name})
参数说明数据类型
container

A reference to a Layout object, a graphics layer in a Map object, or a GroupElement object in a layout or a graphics layer.

Object
element_list
[element_list,...]

A list of elements that will be placed in the newly created group.

注:

You can not create an empty group element, there must be existing elements to place in the group.

List
name

An optional string that represents the name of the new GroupElement. If a name is not provided, the default name value will follow the automatic sequencing nomenclature, for example, Group Element, Group Element 1, Group Element 2, and so on.

String
返回值
数据类型说明
GroupElement

如果提供了变量,则其将引用新返回的 GroupElement 对象。

此方法位于 ArcGISProject 对象上,因为 container 属性允许您在 Layout 对象、Map 对象的图形图层或者布局或图形图层的 GroupElement 对象中创建图形元素。

您无法创建新的空白组元素。 而是需要具备现有元素以嵌入到组元素中。 如果容器为布局或图形图层,则将在根级别创建组。 如果容器引用现有组元素,则将创建子组元素。 列表中的第一个元素将为组中的第一个元素,列表中的下一个元素将出现在内容窗格中第一个元素的下方,依此类推。

有关详细信息和代码示例,请参阅 GroupElement 类帮助主题。

createLayout (page_width, page_height, page_units, {name})
参数说明数据类型
page_width

A double that specifies the width of a layout and is based on the page_units.

Double
page_height

A double that specifies the height of a layout and is based on the page_units.

Double
page_units

One of the following page units must be provided to describe the page_width and page_height values.

  • CENTIMETERPage units are in centimeters.
  • INCHPage units are in inches.
  • MILLIMETERPage units are in millimeters.
  • POINTPage units are in points where 72 points is 1 inch or 2.54 centimeters.
String
name

A string that represents the name of the new layout. If a name is not provided, the default name will follow the sequencing nomenclature, for example, Layout, Layout1, Layout2.

String
返回值
数据类型说明
Layout

如果选择提供了变量引用,则其将表示对新 Layout 对象的引用。

此方法会返回对新 Layout 对象的引用。 如果您希望查看布局并在视图中将其激活,请在 Layout 上调用 openView 方法。 接下来的步骤是借助 Layout 类或 ArcGISProject 类上不同的构造函数方法,使用新的布局元素对其进行填充。

createMap ({name}, {map_type})
参数说明数据类型
name

A string that represents the name of the new map. If a name is not provided, the default name will follow the sequencing nomenclature, for example, Map, Map1, Map2.

String
map_type

The type of map to be created and are defined by the keywords below.

  • GLOBEA new global scene
  • MAPA new map
  • SCENEA new local scene

(默认值为 Map)

String
返回值
数据类型说明
Map

如果指定了变量参考,将表示受支持的 map_type 对象之一。

此方法会返回对新地图类的参考。 如果脚本在应用程序内运行,则将应用在工程设置中指定的底图。 如果脚本独立运行,则将自动添加地形底图。

createPictureElement (container, geometry, path, {name}, {lock_aspect_ratio})
参数说明数据类型
container

A reference to a Layout object, a graphics layer object in a Map, or a GroupElement object in a layout or a graphics layer.

Object
geometry

The appropriate Point, or Polygon object that will be used to construct the picture element. Page units should be used for layouts and map units should be used for elements in a graphics layer.

Object
path

A string that represents the full path and file name of the location of the picture.

String
name

An optional string that represents the name of the new PictureElement. If a name is not provided, the default name value will follow the automatic sequencing nomenclature, for example, Picture, Picture 1, Picture 2, and so on.

String
lock_aspect_ratio

A Boolean that controls how the picture is inserted into the envelope. If set to False, the image will be stretched to fill the entire area of the envelope.

(默认值为 True)

Boolean
返回值
数据类型说明
PictureElement

如果提供了变量,则其将引用新返回的 PictureElement 对象。

此方法位于 ArcGISProject 对象上,因为 container 属性允许您在 Layout 对象、Map 对象的图形图层或者布局或图形图层的 GroupElement 对象中创建图形元素。

如果使用点几何创建了元素,则点位置将表示 anchor 位置,并将基于其像素数在全尺寸下添加。 稍后,可以使用 elementWidthelementHeight 属性调整元素的大小。 如果图片在创建时使用非矩形面形状,则将使用包含所有坐标的最小包络矩形。

有关详细信息和代码示例,请参阅 PictureElement 类帮助主题。

createPredefinedGraphicElement (container, geometry, shape_type, {style_item}, {name}, {lock_aspect_ratio})
参数说明数据类型
container

A reference to a Layout object, a graphics layer in a Map object, or a GroupElement object in a layout or a graphics layer.

Object
geometry

The appropriate Point or Polygon object that will be used to construct the predefined GraphicElement object. Page units should be used for layouts and map units should be used for elements in a graphics layer.

Object
shape_type

A string constant that represents the predefined shape that will be created. The following is a list of valid values:

  • CIRCLEA predefined circle shape will be created.
  • CLOUDA predefined cloud shape will be created.
  • CROSSA predefined cross shape will be created.
  • ELLIPSEA predefined ellipse shape will be created.
  • HALF_CIRCLEA predefined half circle shape will be created.
  • RECTANGLEA predefined rectangle shape will be created.
  • RIGHT_TRIANGLEA predefined right triangle shape will be created.
  • ROUNDED_RECTANGLEA predefined rounded rectangle shape will be created.
  • TRIANGLEA predefined triangle shape will be created.
  • XA predefined X shape will be created.
String
style_item

An optional reference to a StyleItem. The style's intended geometry must match the geometry input parameter. If a style_item value is not specified, a default style item will be applied.

String
name

An optional string that represents the name of the new GraphicElement. If a name is not provided, the default name value will follow the automatic sequencing nomenclature, for example, Circle, Circle 1, Circle 2, and so on.

String
lock_aspect_ratio

An optional Boolean that controls how the element can be resized. For example, if the value is True, setting the elementHeight value will also set the elementWidth value proportionally.

(默认值为 True)

Boolean
返回值
数据类型说明
GraphicElement

如果提供了变量,则其将引用新返回的 GraphicElement 对象。

此方法位于 ArcGISProject 对象上,因为 container 属性允许您在 Layout 对象、Map 对象的图形图层或者布局或图形图层的 GroupElement 对象中创建图形元素。

如果元素使用点几何进行创建,则点位置将代表 anchor 位置,并且存在默认大小。 稍后,可以使用 elementWidthelementHeight 属性调整元素的大小。 createGraphicElement 方法非常类似,但是它允许创建自定义形状。

有关详细信息和代码示例,请参阅 GraphicElement 类帮助主题。

createTextElement (container, geometry, text_type, text, {text_size}, {font_family_name}, {font_style_name}, {style_item}, {name}, {lock_aspect_ratio})
参数说明数据类型
container

A Layout object, a graphics layer in a Map object, or a GroupElement object in a layout or a graphics layer.

Object
geometry

The appropriate Point, Polyline, or Polygon object that will be used to construct the text element. Use page units for layouts and map units for elements in a graphics layer.

Object
text_type

Specifies the type of text that will be created. The following is a list of valid values:

  • CIRCLECircle paragraph text will be created.
  • ELLIPSEEllipse paragraph text will be created.
  • LINEText along a polyline will be created.
  • POINTStraight text will be created.
  • POLYGONRectangle or polygon paragraph text will be created.
String
text

The text string associated with the element.

String
text_size

The size of the text in points.

Double
font_family_name

The text symbol font associated with the element.

注:

The value that appears in the Font name drop-down list on the ribbon does not always match the font_style_name property. Variable fonts contain named instances of font styles and also allow customization. Before setting a value, you can set it on the ribbon and verify the property value returned.

String
font_style_name

The font style name. Depending on the font, the style may include regular, bold, italic, any combination of these, or an extended list.

注:

The value that appears in the Font style drop-down list on the ribbon does not always match the font_style_name property. Variable fonts contain named instances of font styles and also allow customization. Before setting a value, you can set it on the ribbon and verify the property value returned.

String
style_item

A StyleItem object. The style's intended geometry must match the geometry input parameter. If a style_item value is not provided, a default style item will be applied.

String
name

The new TextElement name. If no name is provided, the default name value will follow the automatic sequencing nomenclature, for example, Point, Point 1, Point 2, and so on.

String
lock_aspect_ratio

Specifies whether the element can be resized. For example, if the value is True, setting the elementHeight value will also set the elementWidth value proportionally. This setting does not apply to point text.

(默认值为 True)

Boolean
返回值
数据类型说明
TextElement

如果提供了变量,则其将引用新返回的 TextElement 对象。

此方法位于 ArcGISProject 对象上,因为 container 属性允许您在 Layout 对象、Map 对象的图形图层或者布局或图形图层的 GroupElement 对象中创建组元素。

如果文本元素使用点几何,则点位置将表示 anchor 位置,并且存在默认大小。 您可以使用 elementWidthelementHeight 属性调整元素的大小。

有关详细信息和代码示例,请参阅 TextElement 帮助主题。

deleteItem (project_item)
参数说明数据类型
project_item

An object that represents a supported project item to be deleted.

Object

项目将从工程中永久删除。 删除项目可能影响其他项目。 例如,如果删除在布局中使用的地图,参考地图的地图框将失去对地图的参考,map 属性将设置为 None

importDocument (document_path, {include_layout}, {reuse_existing_maps})
参数说明数据类型
document_path

A string that includes the system path and name of a document (.mxd, .3dd, or .sxd) or a map file (.mapx), layout file ( .pagx), or report file (.rptx).

String
include_layout

A Boolean parameter indicating whether the layout from a map document (.mxd) is imported. If set to True, the layout and all data frames are imported. If set to False, only the data frames are imported. This parameter is ignored for other file types.

(默认值为 True)

Boolean
reuse_existing_maps

A Boolean parameter to prevent the creation of duplicate maps in the project. If reuse_existing_maps is set to True, it checks the project for the maps referenced in the imported file and only copies maps that don't already exist in the project. There may be cases in which maps have the same name in different imported sources, so you may want to set this value to False.

(默认值为 False)

Boolean
返回值
数据类型说明
Map

导入地图文档 (.mxd) 时,如果 include_layoutTrue,则将返回对布局的引用。 如果 include_layoutFalse,将返回地图文档中的第一个地图。 将返回 globe (.3dd) 或场景 (.sxd) 文档中的唯一一张地图。 对应的布局.pagx 文件返回,报表.rptx 文件返回。

此方法一次导入一个文档。 要导入多个文档,对每个文档运行一次该方法。 地图文档 (.mxd) 始终具有布局。 迁移地图文档时,如果不想导入布局,则设置 include_layout=False

listBasemaps ({wildcard})
参数说明数据类型
wildcard

A wildcard is based on the label as it appears in the basemap gallery in the application and is not case sensitive. A combination of asterisks (*) and characters can be used to help limit the resulting list.

(默认值为 None)

String
返回值
数据类型说明
List

返回 String 对象的 Python 列表。

即使仅返回一个底图,listBasemaps 方法也始终返回一个列表对象,因此请使用索引编号以返回字符串。 listBasemaps 的输出后续可用于 Map 类的 addBasemap 方法中。

以下脚本用于向地图添加底图。


p = arcpy.mp.ArcGISProject('current')
bm = p.listBasemaps('National Geographic*')[0]
m = p.listMaps('Yosemite National Park')[0]
m.addBasemap(bm)
listBrokenDataSources ()
返回值
数据类型说明
List

Layer 和/或 Table 对象的 Python 列表。

listBrokenDataSources 方法始终返回 Python 列表对象,即使返回一个损坏的图层或表。

listColorRamps ({wildcard})
参数说明数据类型
wildcard

通配符将基于色带名称显示在应用程序中。星号 (*) 和字符的组合可用于帮助限制生成的列表。

(默认值为 None)

String
返回值
数据类型说明
List

将返回 ColorRamp 对象列表。

在一个工程中,可能会有多个色带使用相同的名称。创作工程时,采用可通过唯一名称轻松进行搜索的色带名称非常重要。索引编号可用于返回一个特定的色带。例如,以下行可以返回列表中的第一个色带对象:cr = aprx.listColorRamps("Black*")[0]

listLayouts ({wildcard})
参数说明数据类型
wildcard

通配符基于布局名称且不区分大小写。星号 (*) 和字符的组合可用于帮助限制生成的列表。

(默认值为 None)

String
返回值
数据类型说明
List

ArcGIS 工程中的 Layout 对象的 Python 列表。

返回 ArcGIS 工程 (.aprx) 中的 Layout 对象的 Python 列表。

listMaps ({wildcard})
参数说明数据类型
wildcard

通配符基于地图名称且不区分大小写。星号 (*) 和字符的组合可用于帮助限制生成的列表。

(默认值为 None)

String
返回值
数据类型说明
List

ArcGIS 工程中的 Map 对象的 Python 列表。

返回 ArcGIS 工程 (.aprx) 中的 Map 对象的 Python 列表。

listReports ({wildcard})
参数说明数据类型
wildcard

通配符基于报表名称且不区分大小写。星号 (*) 和字符的组合可用于帮助限制生成的列表。

(默认值为 None)

String
返回值
数据类型说明
List

ArcGIS 工程中的报表对象的 Python 列表。

返回 ArcGIS 工程 (.aprx) 中的报表对象的 Python 列表。

listStyleItems (style, style_class, {wildcard})
参数说明数据类型
style

A string that represents either a system style name such as ArcGIS 2D, a personal style such as Favorites, or a custom .stylx file.

注:

Styles must exist in the project before they can be referenced using listStyleItems. Custom .stylx files must be loaded and saved in a project. They are referenced by passing in their full path and filename, not by their name only such as with system styles.

(默认值为 None)

String
style_class

A string that represents the class of the style items that will be created or modified as they will appear in the Catalog View window.

  • LEGENDLegend elements will be created or modified.
  • LINEPolyline graphic elements will be created or modified.
  • NORTH_ARROWNorth arrow map surround elements will be created or modified.
  • POINTPoint graphic elements will be created or modified.
  • POLYGONPolygon graphic elements will be created or modified.
  • SCALE_BARNorth arrow map surround elements will be created or modified.
  • TEXTText graphic elements will be created or modified.

(默认值为 None)

String
wildcard

A wildcard based on the style item name as it appears in the application. A combination of asterisks (*) and characters can be used to limit the length of the resulting list.

(默认值为 None)

String
返回值
数据类型说明
List

返回 StyleItem 对象列表。

在一个工程中,可能会有多个具有相同名称的样式项。 如果是这种情况,则除了 wildcard 参数之外,您还可以使用 categorytags 等属性来验证是否拥有所需的样式项。 请参阅 StyleItem 类帮助主题中的代码示例。

save ()

将更改保存至 ArcGISProject (.aprx)。已保存此项目,同时项目变量继续引用原始 ArcGISProject 对象。

saveACopy (file_name)
参数说明数据类型
file_name

用来将 ArcGISProject (.aprx) 保存到新文件路径或另存为新文件名的字符串。

String

该方法会创建新输出工程文件,但工程变量继续引用原始 ArcGISProject 对象。并不会复制工程文件夹中的所有内容。

updateConnectionProperties (current_connection_info, new_connection_info, {auto_update_joins_and_relates}, {validate}, {ignore_case})
参数说明数据类型
current_connection_info

A string that represents the workspace path or a Python dictionary that contains connection properties to the source you want to update. If an empty string or None is used in current_connection_info, all connection properties will be replaced with the new_workspace_info, depending on the value of the validate parameter.

String
new_connection_info

A string that represents the workspace path or a Python dictionary that contains connection properties with the new source information.

String
auto_update_joins_and_relates

If set to True, the updateConnectionProperties method will also update the connections for associated joins or relates.

(默认值为 True)

Boolean
validate

If set to True, the connection properties will only be updated if the new_connection_info value is a valid connection. If it is not valid, the connection will not be replaced. If set to False, the method will set all connections to match the new_connection_info value, regardless of a valid match. In this case, if a match does not exist, the data sources would be broken.

(默认值为 True)

Boolean
ignore_case

Determines whether searches will be case sensitive. By default, queries are case sensitive. To perform queries that are not case sensitive, set ignore_case to True.

(默认值为 False)

Boolean

有关更详细的说明、参数信息、情景和代码示例,请参阅更新和修复数据源

updateDatabases (databases, {validate})
参数说明数据类型
databases
[databases,...]

A list of Python dictionaries that each contain properties to an individual database. The dictionary keys are defined below.

  • databasePathA local or UNC path to a database.
  • isDefaultDatabaseThe default geodatabase. One valid geodatabase must be set to True.
    注:

    This property can be locked by systems administrators through Application settings.

List
validate

If set to True, the database will only be added if the databasePath is a valid database. If it is not valid, the database will not be added and the function will return the dictionary as an invalid database. If set to False, the method will add all the databases to the project, regardless of whether the database can be connected to.

(默认值为 True)

Boolean
返回值
数据类型说明
List

无效数据库的列表。

要更新工程的数据库,必须同时设置整个数据库列表。 无法同时添加、移除或更新单个数据库。 可以从头开始构建新列表,或可以修改 databases 属性返回的列表,然后使用 updateDatabases 方法将整个列表重新推送回工程。

updateFolderConnections (folder_connections, {validate})
参数说明数据类型
folder_connections
[folder_connections,...]

A list of Python dictionaries that each contain connection properties to an individual folder. The dictionary keys are defined below.

  • connectionStringA local or UNC path to a system folder.
  • aliasAn alternative label for a folder connection. If left as an empty string, the alias will match the connectionString value.
  • isHomeFolderThe default home folder. One folder must be set to True.
    注:

    This property can be locked by systems administrators through Application settings.

List
validate

If set to True, the folder will only be added if the connectionString is a valid path. If it is not valid, the folder will not be added and the function will return the dictionary as an invalid folder. If set to False, the method will add all the folders to the project, regardless of whether the folder is valid.

(默认值为 True)

Boolean
返回值
数据类型说明
List

没有有效连接的文件夹列表。

要更新工程的文件夹连接,必须同时设置整个数据库列表。 不能一次添加、移除或更新单一文件夹连接。 可以从头开始构建新列表,或可以修改 folderConnections 属性返回的列表,然后使用 updateFolderConnections 方法将整个列表重新推送回工程。

代码示例

ArcGISProject 示例 1

下面的脚本演示了如何将文档导入到现有 ArcGIS Pro 模板工程。 同时还设置了一些默认工程设置并将结果保存到新工程文件。

import arcpy
#Reference a blank, template project on disk
p = arcpy.mp.ArcGISProject(r"C:\Projects\blank.aprx")

#Import documents set up default GDB and toolbox
p.importDocument(r"C:\Projects\YosemiteNP\Documents\Yosemite.mxd")
p.importDocument(r"C:\Projects\YosemiteNP\Documents\Yosemite_3DViews.3dd")

#Set up default GDB and toolbox
p.defaultGeodatabase = r"C:\Projects\YosemiteNP\Data_Vector\YosemiteData.gdb"
p.defaultToolbox = r"C:\Projects\YosemiteNP\Analysis\AnalysisTools.tbx"

#Save out to a new, different project
p.saveACopy(r"C:\Projects\YosemiteNP\Yosemite.aprx")
ArcGISProject 示例 2

以下脚本用于打印工程中对象的名称。 脚本使用关键字 CURRENT,因此应从 Python 窗口中运行。 脚本将打印每个地图的名称,后跟其图层列表。 然后,将打印各个布局的名称以及页面大小信息。

p = arcpy.mp.ArcGISProject('CURRENT')

#Project information
print(f'Project: {p.filePath}')
print(f' Version: {p.filePath}')
print(f' Last saved: {p.dateSaved}')

#Loop through each map
print('Maps and Layers:')
for m in p.listMaps():
    print(' Map: ' + m.name)
    for lyr in m.listLayers():
        print('  Layer: ' + lyr.name)
        
#Loop through each layout
print('Layouts:')
for lyt in p.listLayouts():
    print(f' Name: {lyt.name}')
    print(f'  W/H: {lyt.pageWidth} x {lyt.pageHeight}')
    print(f'  Units: {lyt.pageUnits}')
ArcGISProject 示例 3

下面的脚本使用了关键字 CURRENT,因此应从 Python 窗口运行此脚本。 该脚本将复制现有地图、向其添加新图层、设置控制新打开的视图范围的地图默认相机属性、将地图视图导出为 PDF 并从工程中移除新创建的地图。

p = arcpy.mp.ArcGISProject('CURRENT')

#Create a copy of an existing map
existingMap = p.listMaps('Yosemite National Park')[0]
rangerMap = p.copyItem(existingMap, new_name='Ranger Stations')

#Add ranger stations layer file
lyrx = arcpy.mp.LayerFile(r'C:\Projects\YosemiteNP\LayerFiles\Ranger Stations.lyrx')
rangerMap.addLayer(lyrx)

#Close any current layout or map views
p.closeViews('MAPS_AND_LAYOUTS')

#Set the default map camera to the extent of the park boundary before opening the new view
#default camera only affects newly opened views
lyr = rangerMap.listLayers('*Park Boundary')[1]
rangerMap.defaultCamera.setExtent(arcpy.Describe(lyr).extent)
rangerMap.openView()

#export the newly opened active view to PDF, then delete the new map
mv = p.activeView
mv.exportToPDF(r'C:\Temp\RangerStations.pdf', width=700, height=500, resolution=96)

#Optionally delete the temporary map when the export is complete
p.deleteItem(rangerMap)
ArcGISProject 示例 4

以下脚本可遍历工程中的所有文件地理数据库图层,并将各个唯一的工作空间路径添加到文件夹工程项目文件夹。

import arcpy, os
p = arcpy.mp.ArcGISProject(r'C:\Projects\YosemiteNP\Yosemite.aprx')

#Check project read-state before continuing
if p.isReadOnly:
  print('WARNING: project is already opened. Exiting.')
  exit

folderList = [p.homeFolder]
for m in p.listMaps():
  for l in m.listLayers():
    if not l.isWebLayer:
      if not l.isBasemapLayer:
        if l.supports('DATASOURCE'):
          dirPath = os.path.dirname(l.dataSource)
          #Parce out GDB folders
          pathParts = dirPath.split(os.sep)
          for part in pathParts:
            if part.endswith(".gdb"):
              gdbName = part
              dirPath = dirPath.split("\\"+gdbName, 1)[0]
          #Add unique path to list
          if dirPath not in folderList:
            folderList.append(dirPath)
folderList.sort()
for f in folderList:
    print(f)
print(f'Total Unique Folders: {len(folderList)}')

#Add each folder connection from FolderList, there MUST be one default folder.

fcList = []
for folder in folderList:
  if folder == r'C:\Projects\YosemiteNP':
    defName2 = r'Default Folder'
    fcDict = {'connectionString':folder, 'alias':defName2, 'isHomeFolder':True}

  else:
    fcDict = {'connectionString':folder, 'alias':'', 'isHomeFolder':False}

  fcList.append(fcDict)

bfc = p.updateFolderConnections(fcList, validate=False)
print(f'Broken folder connections: {len(bfc)}')

p.saveACopy(r'C:\Projects\YosemiteNP\Yosemite_Output.aprx')
ArcGISProject 示例 5

以下脚本可将新的文件地理数据库添加到数据库工程项目文件夹,提供工程中数据的快速访问方式。

import arcpy, os
path = r'C:\Projects\YosemiteNP'

p = arcpy.mp.ArcGISProject(os.path.join(path, 'Yosemite.aprx'))
#Check project read-state before continuing
if p.isReadOnly:
  print('WARNING: project is already opened. Exiting.')
  exit

db = p.databases

#Append new fGDBs in addition to the already existing default database
db.append({'databasePath' : os.path.join(path, r'Data_Geology\Geology.gdb'),
           'isDefaultDatabase': False})
db.append({'databasePath' : os.path.join(path, r'Data_Elev\Elevation.gdb'),
           'isDefaultDatabase': False})
db.append({'databasePath': os.path.join(path, r'\Data_LandCover\LandCover.gdb'),
           'isDefaultDatabase': False})

p.updateDatabases(db, True)
p.saveACopy(os.path.join(path, 'Yosemite_newGDBs.aprx'))
ArcGISProject 示例 6

以下脚本可在工程中创建一个布局,并使用引用的系统样式创建预定义的图形元素。 将使用一个函数为添加到布局的每个矩形图形创建包络矩形。

def MakeRec_LL(llx, lly, w, h):
    xyRecList = [[llx, lly], [llx, lly+h], [llx+w,lly+h], [llx+w,lly], [llx,lly]]
    xyRecList = [[1,1],[1, 2], [2.75, 2], [2.75, 1], [1, 1]]
    array = arcpy.Array([arcpy.Point(*coords) for coords in xyRecList])
    rec = arcpy.Polygon(array)
    return rec

p = arcpy.mp.ArcGISProject('CURRENT')
lyt = p.createLayout(6, 3, 'INCH', 'New Layout with Rectangles')

#Construct a pre-defined rectangle graphic element using a system style item
# and a rectangle function that takes x/y min/max and a width/height
# using the lower left corner as a start location

polyStyle = p.listStyleItems('ArcGIS 2D', 'Polygon', 'Orchard')[0]

p.createPredefinedGraphicElement(lyt, MakeRec_LL(1, 1, 1.75, 1), 'RECTANGLE',
                                 polyStyle, 'ArcPy_Rectangle_Env',
                                 lock_aspect_ratio=False)

#Construct the same element above using a point location
rec = p.createPredefinedGraphicElement(lyt, arcpy.Point(3, 1), 'RECTANGLE',
                                       polyStyle, 'ArcPy_Rectangle_Pt',
                                       lock_aspect_ratio=False)
rec.elementWidth = 1.75
rec.elementHeight = 1

lyt.openView()
ArcGISProject 示例 7

以下脚本可创建包含图形图层的地图。 接下来,可将两个图片添加到图形图层中的新图层组中。 将使用一个函数为每个图片创建包络矩形,并且它们将偏移 3000000 个地图单位。

def MakeRec_UL(ulx, uly, w, h):
    xyRecList = [[ulx, uly], [ulx+w, uly], [ulx+w,uly-h], [ulx,uly-h], [ulx,uly]]
    array = arcpy.Array([arcpy.Point(*coords) for coords in xyRecList])
    rec = arcpy.Polygon(array)
    return rec
        
p = arcpy.mp.ArcGISProject('current')
m = p.createMap('New Map', 'Map') #WGS 1984 Web Mercator (auxiliary sphere)
gl = m.createGraphicsLayer('New Graphics Layer')

###Replace with pictures of YOUR favorite pets!
picPath1 = r'C:\Projects\Fenway.jpg'
picPath2 = r'C:\Projects\Chowdah.png'

x = -13000000; y = 5000000; w = 1000000; h = 1500000

pic1 = p.createPictureElement(gl, MakeRec_UL(x, y, w, h), picPath1, 'Fenway')
pic2 = p.createPictureElement(gl, MakeRec_UL(x+3000000, y, w, h), picPath2, 'Chowdah')
m.openView()

newGroup = p.createGroupElement(gl, [pic1, pic2], 'Favorite Pets')