Skip to main content

closeViews

汇总

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 对象或使用 createReport 创建 Report 对象。

注:

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 )之前确定工程的读取状态。

语法

closeViews()

属性

名称 说明 数据类型

activeMap

(只读)

返回与应用程序内部焦点视图相关联的 map 对象。 布局视图可以包含多个引用不同地图的地图框,但同一时间只能有一个地图框处于活动状态。 该属性将返回与活动地图框相关联的 map 。 如果未找到关联的 map ,则将返回 NoneType

注:

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

Map

activeView

(只读)

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

注:

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

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

(读取和写入)

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

Metadata

styles

(只读)

返回工程中存在的样式列表。 列表中的值表示字符串,这些字符串可以是系统样式关键字(例如 ArcGIS 2D ),也可以是自定义 .stylx 文件的完整路径。 要修改样式列表,请参阅 updateStyles 方法。

注:

收藏夹样式不会从 styles 属性中返回。 由于收藏夹样式已链接到用户账户,因此在工程中始终可用。 它不与工程关联,无法使用 arcpy.mp API 进行管理。

List

toolboxes

(只读)

返回 Python 字典列表,每个字典表示工程中各个工具箱的属性。 要修改工具箱,请参阅 updateToolboxes 方法。

List

方法

closeViews({view_type})

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

名称 说明 数据类型

view_type

(可选)

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

  • LAYOUTS—Close all open layout view panes.

  • MAPS—Close all open map view panes.

  • MAPS_AND_LAYOUTS—Close all open layout and map view panes.

  • REPORTS—Close all open report view panes.

  • TABLES—Close all open table view panes.

(默认值为 MAPS_AND_LAYOUTS)

String

copyItem(project_item, {new_name})

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

名称 说明 数据类型

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})

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

名称 说明 数据类型

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 对象。

createGroupElement(container, element_list[element_list,...], {name})

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

名称 说明 数据类型

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 对象。

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

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

名称 说明 数据类型

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.

  • CENTIMETER—Page units are in centimeters.

  • INCH—Page units are in inches.

  • MILLIMETER—Page units are in millimeters.

  • POINT—Page 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 对象的引用。

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.

  • GLOBE—A new global scene

  • MAP—A new map

  • SCENE—A new local scene

(默认值为 Map)

String

返回值

数据类型 说明

Map

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

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

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

名称 说明 数据类型

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 对象。

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

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

名称 说明 数据类型

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:

  • CIRCLE—A predefined circle shape will be created.

  • CLOUD—A predefined cloud shape will be created.

  • CROSS—A predefined cross shape will be created.

  • ELLIPSE—A predefined ellipse shape will be created.

  • HALF_CIRCLE—A predefined half circle shape will be created.

  • RECTANGLE—A predefined rectangle shape will be created.

  • RIGHT_TRIANGLE—A predefined right triangle shape will be created.

  • ROUNDED_RECTANGLE—A predefined rounded rectangle shape will be created.

  • TRIANGLE—A predefined triangle shape will be created.

  • X—A 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 对象。

createReport(page_info, data_source, {fields[fields,...]}, {statistics[statistics,...]}, {name}, {template}, {styling})

createReport 方法生成的报表会自动添加到 目录 窗格中。

名称 说明 数据类型

page_info

A dictionary that specifies the page width, height, units, and margins for the new report.

The page width and height are based on the units key value.

  • CENTIMETER—The page units will be centimeters.

  • INCH—The page units will be inches.

  • MILLIMETER—The page units will be millimeters.

  • POINT—The page units will be points in which 72 points is 1 inch or 2.54 centimeters.

The page margins restrict editable space for the report. An 8.5 inch by 11 inch report, for example, with NORMAL margins will display as 6.5 inches by 9 inches in a new Report view.

The margin key values are defined as follows:

  • NORMAL—The page margins will be 1 inch, 72 points, 2.54 centimeters, or 25.4 millimeters.

  • NARROW—The page margins will be 0.5 inches, 36 points, 1.27 centimeters, or12.7 millimeters.

  • MODERATE—The page margins will be 1 inch, 72 points, 2.54 centimeters, or 25.4 millimeters for top and bottom margins and 0.75 inch, 54 points, 1.905 centimeters, or 12.05 millimeters for left and right margins.

  • WIDE—The page margins will be 1 inch, 72 points, 2.54 centimeters, or 25.4 millimeters for top and bottom margins and 2 inches, 144 points, 5.08 centimeters, or 50.8 millimeters for left and right margins.

Dictionary

data_source

A Layer object, a Table object, or a string that represents the path to an external data source.

Object

fields[fields,...]

(可选)

A list of field dictionaries that include the following keys:

  • fieldName—The field name for the report.

  • sortInfo—The field sorting information for the report.

  • groupField—Set to True if the field should be used as a group.

The sortInfo values are defined as follows:

  • ASC—Sort the field in ascending order.

  • DESC—Sort the field in descending order.

  • NONE—Do not sort the field, use the database order.

Dictionary

statistics[statistics,...]

(可选)

A list of statistic dictionaries that include field name and statistic type. If a value is specified, the fields parameter is required. The keys for the dictionary are defined as follows:

  • fieldName—The field name for the statistic.

  • statistic—The statistic type for the report.

The acceptable statistic values are defined as follows:

  • COUNT—The row count for a group or report will be identified.

  • MEAN—The mean of a numeric field for a group or report will be computed.

  • MEDIAN—The median of a numeric field for a group or report will be computed.

  • SUM—The sum of a numeric field for a group or report will be computed.

  • STD_DEV—The standard deviation of a numeric field for a group or report. will be computed

  • MAX—The maximum of a field for a group or report will be identified.

  • MIN—The minimum of a field for a group or report will be identified.

Dictionary

name

(可选)

A string that represents the name of the new report. If no name is provided, the default name value will follow the sequencing nomenclature, for example, Report, Report1, Report2.

String

template

(可选)

A string that represents a default template for the new report. The acceptable values are defined as follows:

  • ATTR_LIST—Generates a list of rows with columns from the chosen fields.

  • ATTR_LIST_GROUP—Generates a list of rows with columns from the chosen fields, grouped by a unique field.

  • BASIC_SUM—Generates a list of the specified summary statistics. No individual rows are listed.

  • BASIC_SUM_GROUP—Generates a list of the specified summary statistics, grouped by a unique field. No individual rows are listed.

  • PAGE_PER_FEATURE—Generates a separate page for each feature listing the chosen fields.

(默认值为 ATTR_LIST)

String

styling

(可选)

A string that represents a default styling for the new report. The acceptable values are defined as follows:

  • BLACK_AND_WHITE—Greyscale styling with black fonts.

  • COOL_TONES—Blue lines and backgrounds with gray fonts.

  • WARM_TONES—Orange lines and backgrounds with gray fonts.

  • NO_STYLING—No styling.

(默认值为 BLACK_AND_WHITE)

String

返回值

数据类型 说明

Report

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

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

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

名称 说明 数据类型

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:

  • CIRCLE—Circle paragraph text will be created.

  • ELLIPSE—Ellipse paragraph text will be created.

  • LINE—Text along a polyline will be created.

  • POINT—Straight text will be created.

  • POLYGON—Rectangle 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.

(默认值为 False)

Boolean

返回值

数据类型 说明

TextElement

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

deleteItem(project_item)

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

名称 说明 数据类型

project_item

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

Object

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

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

名称 说明 数据类型

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

log_files

(可选)

A Boolean parameter that controls if log files are written to the ImportLog folder in the project's homeFolder. Log files can be useful for identifying possible warnings and errors during import but they can also accumulate if not properly managed.

(默认值为 True)

Boolean

返回值

数据类型 说明

Object

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

listBasemaps({wildcard})

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

名称 说明 数据类型

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 列表。

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

p = arcpy.mp.ArcGISProject('current')
bm = p.listBasemaps('National Geographic*')[0]
m = p.listMaps('Yosemite National Park')[0]
m.addBasemap(bm)

listBrokenDataSources()

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

返回值

数据类型 说明

List

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

listColorRamps({wildcard})

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

名称 说明 数据类型

wildcard

(可选)

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

(默认值为 None)

String

返回值

数据类型 说明

List

将返回 ColorRamp 对象列表。

listLayouts({wildcard})

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

名称 说明 数据类型

wildcard

(可选)

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

(默认值为 None)

String

返回值

数据类型 说明

List

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

listMaps({wildcard})

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

名称 说明 数据类型

wildcard

(可选)

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

(默认值为 None)

String

返回值

数据类型 说明

List

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

listReports({wildcard})

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

名称 说明 数据类型

wildcard

(可选)

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

(默认值为 None)

String

返回值

数据类型 说明

List

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

listStyleItems(style, {style_class}, {wildcard})

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

名称 说明 数据类型

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.

(默认值为 None)

String

style_class

(可选)

A string that represents the class of the style items as they appear in the Catalog View window.

  • LEGEND—Legend elements

  • LEGEND_ITEM—Legend items

  • LINE—Polyline graphic elements

  • NORTH_ARROW—North arrow map surround elements

  • POINT—Point graphic elements

  • POLYGON—Polygon graphic elements

  • SCALE_BAR—North arrow map surround elements

  • TABLE_FRAME—Table frame elements

  • TEXT—Text graphic elements

(默认值为 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 对象列表。

save()

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

saveACopy(file_name)

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

名称 说明 数据类型

file_name

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

String

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

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

名称 说明 数据类型

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[databases,...], {validate})

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

名称 说明 数据类型

databases[databases,...]

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

  • databasePath—A local or UNC path to a database.

  • isDefaultDatabase—The 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

无效数据库的列表。

updateFolderConnections(folder_connections[folder_connections,...], {validate})

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

名称 说明 数据类型

folder_connections[folder_connections,...]

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

  • connectionString—A local or UNC path to a system folder.

  • alias—An alternative label for a folder connection. If left as an empty string, the alias will match the connectionString value.

  • isHomeFolder—The 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

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

updateStyles(styles[styles,...])

updateStyles 方法使用字符串列表更新工程样式。

名称 说明 数据类型

styles[styles,...]

A list of strings that are either a system style keyword such as ArcGIS 2D or the full path to a custom .stylx file.

List

返回值

数据类型 说明

List

无法添加的样式列表。 检查拼写或文件路径错误。

以下脚本用于将一个系统样式和一个自定义样式追加到“目录”窗格中当前显示的样式列表中。

p = arcpy.mp.ArcGISProject('current')
s = p.styles
s.append('Pushpins')
s.append(r'C:\Projects\YosemiteNP\Yosemite.stylx')
p.updateStyles(s)

updateToolboxes(toolboxes[toolboxes,...], {validate})

updateToolboxes 方法将使用字典列表替换工程工具箱。

名称 说明 数据类型

toolboxes[toolboxes,...]

A list of Python dictionaries that each contain toolbox information. The dictionary keys are defined below.

  • toolboxPath—A local or UNC path to an ArcGIS toolbox (*.atbx), a Legacy toolbox (*.tbx), or a Python toolbox (*.pyt).

  • validate—The default project toolbox. One toolbox must be set to True.

    注:

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

List

validate

(可选)

Specifies whether all toolboxes will be added to the project. If set to True, the toolbox will only be added if the toolboxPath value is a valid path. If it is not valid, the toolbox will not be added and the function will return the dictionary as an invalid toolbox. If set to False, all the toolboxes will be added to the project, regardless of whether the folder is valid.

(默认值为 True)

Boolean

返回值

数据类型 说明

List

没有有效连接的工具箱列表。

代码示例

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.documentVersion}')
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')
ArcGISProject 示例 68

以下脚本创建一个包含地图图层分组的报表。

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

#Find the report data source
m = p.listMaps('New York')[0]
ds = m.listLayers('Bus Stops')[0]

#Set page info
pi = {'width': 8.5, 'height': 11, 'units': 'INCH', 'margins': 'NORMAL'}

#Define the fields
f = [{'fieldName' : 'Borough', 'sortOrder' : 'ASC', 'groupField' : True},
        {'fieldName' : 'StopID', 'sortOrder' :  'ASC', 'groupField' : False},
        {'fieldName' : 'NumofLines', 'sortOder' : 'None', 'groupField' : False},
        {'fieldName' : 'Capacity', 'sortOrder' : 'None', 'groupField' : False}]

#Define the statistics
s = [{'fieldName' : 'NumofLines', 'statistic' : 'MEAN'},
        {'fieldName' : 'Capacity', 'statistic' : 'MAX'}]

#Create report
r = p.createReport(
    page_info = pi,
    data_source = ds,
    fields = f,
    statistics = s,
    name = 'createReport Example')

#Open new report view
r.openView()