Skip to main content

closeViews

Краткая информация

Объект ArcGISProject обеспечивает доступ к методам и свойствам проекта ArcGIS Pro. Ссылка на этот объект существенна для большинства автоматизированных рабочих процессов для карты.

Обсуждение

Объект ArcGISProject обычно является одним из первых объектов, на которые дается ссылка в скрипте автоматизации карты, потому что он является основной точкой входа для доступа к большинству других объектов в ArcGIS Pro. Ссылки на проект даются с помощью функции ArcGISProject. Ее свойства позволяют получать или задавать параметры проекта, такие как defaultGeodatabase, defaultToolbox, documentVersion, filePath и др. Ее методы позволяют управлять такими элементами проекта, как updateFolderConnections, updateDatabases, createMap и createLayout, а также копировать или удалять некоторые элементы проекта, используя методы copyItem или deleteItem, соответственно.

Метод updateConnectionProperties удобен для замены источников данных в проекте. Источники данных могут быть заменены в объектах ArcGISProject, Map, Layer или Table. Более подробную информацию и примеры кода см. в разделе справки Обновление и исправление источников данных.

Метод importDocument позволяет вам импортировать документы карты (.mxd), глобуса (.3dd) и сцены (.sxd) в проект. Это обеспечивает механизм для автоматизации преобразования этих типов документов в проект ArcGIS Pro. Метод importDocument также позволяет импортировать файлы карт (.mapx), файлы компоновок (.pagx) и файлы отчетов (.rptx) в имеющийся проект.

Получив ссылку на объект ArcGISProject, вы можете перейти к другим объектам, используя различные функции списка. Например, вы можете получить доступ к объекту Map с помощью метода listMaps или к объекту Layout и к объекту Report с помощью методов listLayouts и listReports, соответственно.

На следующей диаграмме, в левой части, показано использование функций списков для навигации и ссылок на объекты в проекте. Диаграмма является лишь примером и не отображает полный набор объектов и методов списков.

Пример диаграммы объектной модели ArcGIS Project, иллюстрирующей использование функций list и create.

На диаграмме выше, в правой части, показано использование многих функций создания объектов. Например, вы можете использовать createMap для создания объекта Map, createLayout для создания Layout или createReport для создания объекта Report.

Примечание:

Методы createGraphicElement, createGroupElement, createPictureElement и createTextElement также доступны в объекте ArcGISProject, поскольку они позволяют создавать элементы либо в объекте Layout, либо графический слой в объекте Map.

Подсказка:

При создании элементов в графическом слое на карте, графические слои ограничены заданным количеством объектов и общим размером. Дополнительные сведения см. в разделе Работа с графическими слоями.

Есть несколько методов и свойств, работающих только со скриптами, которые запускаются внутри приложения, например со скриптами, выполняемыми в окне Python, в блокноте или со скриптами, связанными с инструментами-скриптами. Это и свойства activeMap и activeView, и сам метод closeViews(). Свойство activeMap возвращает объект Map, связанный либо с активным видом карты или с активным фреймом карты в активном виде компоновки. Если эти условия не соблюдаются, будет возвращен NoneType. Свойство activeView возвращает объект MapView, если активен вид карты, или объект Layout, если активен вид компоновки. Если не активен ни один из видов, оба свойства вернут значение None. Эти свойства всегда возвращают None, если скрипт запущен за пределами приложения, так как виды релевантны только в случае, когда приложение открыто. Объект MapView, возвращаемый свойством activeView, является единственным методом изменения экстента, связанного с видом карты. В классе MapView доступно множество функций, позволяющих вам изменить экстент, такие как camera, panToExtent, ZoomToAllLayers и ZoomToBookmarks. Функция closeViews полезна для закрытия определенных типов видов в приложении. Чтобы сосредоточить внимание на определенном виде, закройте все виды и используйте метод openView в классе Layout, Map или Report.

Примечание:

На проекты можно ссылаться несколько раз, но только первая ссылка может быть сохранена напрямую, поскольку остальные ссылки будут открыты только для чтения. У объекта ArcGISProject есть свойство isReadOnly, которое можно использовать для определения состояния чтения проекта перед вызовом метода, такого как saveACopy вместо save.

Синтаксис

closeViews()

Свойства

Имя Объяснение Тип данных

activeMap

(Только для чтения)

Возвращает объект map, связанный с видом, на котором сфокусировано приложение. Вид компоновки может иметь множество фреймов карт, ссылающихся на разные карты, но в каждый момент времени активен только один из них. Свойство вернет map, связанный с активным фреймом карты. Если связанный map не найден, буден возвращен NoneType.

Примечание:

Это свойство предназначено для выполнения из приложения с помощью инструмента-скрипта, окна Python или блокнота. Если скрипт выполняется вне приложения, будет возвращено значение NoneType.

Map

activeView

(Только для чтения)

Возвращает Layout, MapView или Report, в зависимости от текущего вида. Если в проекте ArcGIS Pro нет открытых видов или если активный вид - это не вид карты или вид компоновки (например, диаграмма, таблица, вид Model Builder и т. д.), будет возвращен NoneType.

Примечание:

Это свойство предназначено для выполнения из приложения с помощью инструмента-скрипта, окна Python или блокнота. Если скрипт выполняется вне приложения, будет возвращено значение NoneType.

Object

databases

(Только для чтения)

Возвращает список словарей Python, каждый из которых представляет свойства для отдельных баз данных в проекте. Для изменения баз данных изучите метод updateDatabases.

List

dateSaved

(Только для чтения)

Возвращает объект Python datetime, который сообщает дату последнего сохранения проекта.

DateTime

defaultGeodatabase

(Чтение / Запись)

Местоположение базы геоданных проекта по умолчанию. Строка должна включать полный путь и имя файла базы геоданных.

Примечание:

Это свойство может быть заблокировано системными администраторами через Настройки приложения.

String

defaultToolbox

(Чтение / Запись)

Местоположение набора инструментов проекта по умолчанию. Строка должна включать полный путь и имя файла набора инструментов.

Примечание:

Это свойство может быть заблокировано системными администраторами через Настройки приложения.

String

documentVersion

(Только для чтения)

Возвращает версию документа проекта на основе времени последнего сохранения. Выполнение save или saveACopy приводит к обновлению версии документа, в соответствии с версией приложения.

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

Создает копию существующего элемента проекта layout, map или report.

Имя Объяснение Тип данных

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

Если указана ссылка на переменную, возвращаемый объект будет содержать элемент проекта layout, map или report.

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

Метод createGraphicElement, который создает GraphicElement в определенном container.

Имя Объяснение Тип данных

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 создает GroupElement в указанном container.

Имя Объяснение Тип данных

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, который создает PictureElement в определенном container.

Имя Объяснение Тип данных

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, который создает GraphicElement в определенном container.

Имя Объяснение Тип данных

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, который создает объект TextElement в определенном container.

Имя Объяснение Тип данных

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), глобуса (.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_layout равно True, возвращается ссылка на компоновку. Если include_layout равно False, возвращается первая карта документа. Импортируется только одна карта документа глобуса (.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

Возвращает список Python объектов String.

Следующий скрипт добавляет на карту базовую карту.

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

listBrokenDataSources()

Возвращает список объектов Python Слой (Layer) и/или Таблица (Table), которые имеют поврежденные подключения к оригинальным исходным данным для всех карт проекта.

Возвращаемое значение

Тип данных Объяснение

List

Список объектов Python Слой (Layer) и/или Таблица (Table).

listColorRamps({wildcard})

Метод listColorRamps ссылается на цветовые схемы, доступные в проекте.

Имя Объяснение Тип данных

wildcard

(Дополнительный)

Подстановочный символ основан на имени цветовой схемы, как оно выглядит в приложении. Для наложения ограничений на результирующий список можно использовать сочетание звездочек (*) и символов.

(Значение по умолчанию — None)

String

Возвращаемое значение

Тип данных Объяснение

List

Возвращает список объектов ColorRamp.

listLayouts({wildcard})

Возвращает список Python объектов Layout (Компоновка) в проекте ArcGIS (.aprx).

Имя Объяснение Тип данных

wildcard

(Дополнительный)

Групповой символ базируется на имени компоновки и не является чувствительным к регистру. Для наложения ограничений на результирующий список можно использовать сочетание звездочек (*) и символов.

(Значение по умолчанию — None)

String

Возвращаемое значение

Тип данных Объяснение

List

Список Python объектов Layout (Компоновка) в проекте ArcGIS.

listMaps({wildcard})

Возвращает список Python объектов Map (Карта) в проекте ArcGIS (.aprx).

Имя Объяснение Тип данных

wildcard

(Дополнительный)

Групповой символ базируется на имени карты и не является чувствительным к регистру. Для наложения ограничений на результирующий список можно использовать сочетание звездочек (*) и символов.

(Значение по умолчанию — None)

String

Возвращаемое значение

Тип данных Объяснение

List

Список Python объектов Map (Карта) в проекте ArcGIS.

listReports({wildcard})

Возвращает список Python объектов Отчет в проекте ArcGIS (.aprx).

Имя Объяснение Тип данных

wildcard

(Дополнительный)

Групповой символ базируется на имени отчета и не является чувствительным к регистру. Для наложения ограничений на результирующий список можно использовать сочетание звездочек (*) и символов.

(Значение по умолчанию — None)

String

Возвращаемое значение

Тип данных Объяснение

List

Список Python объектов Отчет в проекте ArcGIS.

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

Следующий скрипт выполняет итерацию по всем слоям файловой базы геоданных в проекте и добавляет каждый уникальный путь к рабочей области в папку Folders с элементами проекта.

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

Следующий скрипт добавляет новые файловые базы геоданных в папку элементов проекта Databases, обеспечивая быстрый доступ к данным из проекта.

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, пример 8

Следующий скрипт создает отчет с группировкой из слоя карты.

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