ArcGISProject

Zusammenfassung

The ArcGISProject object provides access to ArcGIS Pro project methods and properties. A reference to this object is essential for most map automation workflows.

Diskussion

The ArcGISProject object is usually one of the first object references created in a map automation script because it is the main entry point to access most other objects in ArcGIS Pro. A project is referenced using the ArcGISProject function. Its properties allow you to get or set project settings such as defaultGeodatabase, defaultToolbox, documentVersion, filePath and more. Its methods allow you to manage project items such as updateFolderConnections, updateDatabases, createMap, and createLayout, and copy or delete some project items using the copyItem or deleteItem methods, respectively.

The updateConnectionProperties method is useful for replacing data sources in a project. Data sources can be replaced on the ArcGISProject, Map, Layer, or Table object. See the Updating and fixing data sources help topic for more detailed information and code samples.

The importDocument method allows you to import map (.mxd), globe (.3dd), and scene (.sxd) documents into a project. This provides a mechanism for automating the conversion of these document types into the ArcGIS Pro project. The importDocument method also allows you to import map files (.mapx), layout files (.pagx), and report files (.rptx) into an existing project.

Once you have a reference to an ArcGISProject object, you can access other objects using a number of list functions. For example, you can access a Map object using the listMaps method or a Layout object and a Report object using the listLayouts and listReports methods, respectively.

The following diagram illustrates, along the left side, the use of list functions for navigating and referencing the objects in a project. The diagram is only an example and does not display a complete set of objects and list methods.

An example ArcGISProject object model diagram illustrating the use of list and create functions.

The diagram above, along the right side, also illustrates many of the create functions. For example you can use createMap to create a Map object or createLayout to create a Layout object.

Hinweis:

The createGraphicElement, createGroupElement, createPictureElement, and createTextElement methods are also available on the ArcGISProject object because they allow you to create the elements in either a Layout object or a graphics layer in a Map object.

Tipp:

When creating elements in a graphics layer in a map, graphic layers are limited to a set number of features and overall size. See Work with graphics layers for more information.

There are a few methods and properties that only work with scripts that are run in the application such as scripts run in the Python window, a notebook, or those associated with a script tool. These are activeMap and activeView properties and the closeViews() method. The activeMap property will return the Map object associated with either an active map view or the active map frame on an active layout view. If these conditions are not met, NoneType will be returned. The activeView property will return either a MapView object if a map view is active or a Layout object if a layout view is active. If no views are active, both properties will return None. These properties will always return a None value when a script is run outside the application, because views are only relevant when the application is open. The MapView object returned from the activeView property is the only way to change the extent associated with a map view. There are multiple functions available on the MapView class that allow you to change the extent, such as camera, panToExtent, ZoomToAllLayers, and ZoomToBookmarks. The closeViews function is useful for closing specific view types in the application. To give focus to a specific view, close all views and use the openView method on the Layout, Map, or Report class.

Hinweis:

Projects can be referenced multiple times but only the first reference can be saved directly because the other references will be opened as read-only. The ArcGISProject object has an isReadOnly property that can be used to determine a project's read state before calling a method such as saveACopy instead of save.

Eigenschaften

EigenschaftErläuterungDatentyp
activeMap
(Schreibgeschützt)

Returns the map object associated with the focused view within the application. If a layout view is active, it will return the map associated with the active map frame.

Hinweis:

This property is designed to be run from within the application using a script tool, the Python window, or a Notebook. If a script is run outside of the application, a value of None will always be returned.

Map
activeView
(Schreibgeschützt)

Returns a MapView or a Layout, depending on the current view. If the ArcGIS Pro project has no open views, or if the active view is something other than a map view or layout view (for example, a chart, table, Model Builder view, and so on), None will be returned.

Hinweis:

This property is designed to be run from within the application using a script tool or the Python window, or a Notebook. If a script is run outside of the application, a value of None will always be returned.

Object
databases
(Schreibgeschützt)

Returns a list of Python dictionaries, each representing the properties for individual databases in a project. To modify the databases, see the updateDatabases method.

List
dateSaved
(Schreibgeschützt)

Returns a Python datetime object that reports the project's last saved date.

DateTime
defaultGeodatabase
(Lesen und schreiben)

The project's default geodatabase location. The string must include the geodatabase's full path and file name.

Hinweis:

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

String
defaultToolbox
(Lesen und schreiben)

The project's default toolbox location. The string must include the toolbox's full path and file name.

Hinweis:

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

String
documentVersion
(Schreibgeschützt)

Returns the version of the document based on when it was last saved. Running save or saveACopy will update the document version to match the application version.

String
filePath
(Schreibgeschützt)

Returns a string value that reports the fully qualified project path and file name.

String
folderConnections
(Schreibgeschützt)

Returns a list of Python dictionaries, each representing the properties for individual folder connections in a project. To modify folder connections, see the updateFolderConnections method.

List
homeFolder
(Lesen und schreiben)

The project's home folder location. The string must include the full path to the desired location.

Hinweis:

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

String
isReadOnly
(Schreibgeschützt)

Returns True if a project has already been opened in another instance of the application or referenced by another script. Knowing the current state allows you to determine whether you can save the project, for example, or if you need to call saveACopy instead.

Boolean
metadata
(Lesen und schreiben)

Get or set the project's Metadata class information. Note: Setting metadata is dependent on the isReadOnly property value.

Metadata

Methodenübersicht

MethodeErläuterung
closeViews ({view_type})

Close view panes that are currently open in ArcGIS Pro.

copyItem (project_item, {new_name})

Creates a copy of an existing layout, map, or report project item.

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

The createGraphicElement method creates a GraphicElement in the specified container.

createGroupElement (container, element_list, {name})

The createGroupElement method creates a GroupElement in the specified container.

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

The createLayout method creates a Layout that will automatically get added to the Catalog pane.

createMap ({name}, {map_type})

This method creates a map that will automatically get added to the Catalog pane.

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

The createPictureElement method creates a PictureElement in the specified container.

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

The createPredefinedGraphicElement method creates a GraphicElement in the specified container.

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

The createTextElement method creates a TextElement object in the specified container.

deleteItem (project_item)

Deletes a layout, map, or report project item.

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

Imports map (.mxd), globe (.3dd), and scene (.sxd) documents into an ArcGIS Pro project. It can also be used to import the contents of map files (.mapx), layout files (.pagx), and report files (.rptx).

listBasemaps ({wildcard})

The listBasemaps method references basemaps available in a project.

listBrokenDataSources ()

Returns a Python list of Layer and/or Table objects that have broken connections to their original source data for all maps in a project.

listColorRamps ({wildcard})

The listColorRamps method references color ramps available in a project.

listLayouts ({wildcard})

Returns a Python list of Layout objects in an ArcGIS project (.aprx).

listMaps ({wildcard})

Returns a Python list of Map objects in an ArcGIS project (.aprx).

listReports ({wildcard})

Returns a Python list of Report objects in an ArcGIS project (.aprx).

listStyleItems (style, style_class, {wildcard})

The listStyleItems method references system, personal, and custom styles available in a project.

save ()

Saves changes to an ArcGISProject (.aprx).

saveACopy (file_name)

Saves an ArcGISProject (.aprx) to a new file path or name.

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

The updateConnectionProperties method replaces connection properties using a dictionary or a path to a workspace.

updateDatabases (databases, {validate})

The updateDatabases method replaces project databases using a list of dictionaries that describe each database.

updateFolderConnections (folder_connections, {validate})

The updateFolderConnections method replaces project folder connections using a list of dictionaries that describe each connection.

Methoden

closeViews ({view_type})
ParameterErläuterungDatentyp
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.

(Der Standardwert ist MAPS_AND_LAYOUTS)

String

Sometimes it is useful to clean up numerous open views in the application before opening a specific view to see the resulting view with better focus. The method is limited to closing only view panes associated with a layout, map, or a report. This method will also close table views associated with a "MAP".

Hinweis:

This method is designed to be executed from within the application using a script tool, Notebook, or the Python window. It will have no effect if executed outside of the application.

copyItem (project_item, {new_name})
ParameterErläuterungDatentyp
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
Rückgabewert
DatentypErläuterung
Object

If a variable reference is specified, the returned object will represent either a layout, map, or report project item.

This method is appropriate if you want to modify a copy of an existing project item without making changes to the original item. You can copy a layout, a map, or a report project item.

createGraphicElement (container, geometry, {style_item}, {name}, {lock_aspect_ratio})
ParameterErläuterungDatentyp
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.

(Der Standardwert ist True)

Boolean
Rückgabewert
DatentypErläuterung
GraphicElement

If a variable is provided, it will reference the newly returned GraphicElement object.

This method is located on the ArcGISProject object because the container property allows you to create graphic elements in either a Layout object, a graphics layer in a Map object, or a GroupElement object in a layout or graphics layer.

If the element is created using a point geometry, the point location will represent the anchor position and there will be a default size. Later you can resize the element using the elementWidth and elementHeight properties. The createPredefinedGraphicElement method is very similar but it allows you to create common, predefined shapes.

Refer to the GraphicElement class help topic for more information and code samples.

createGroupElement (container, element_list, {name})
ParameterErläuterungDatentyp
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.

Hinweis:

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
Rückgabewert
DatentypErläuterung
GroupElement

If a variable is provided, it will reference the newly returned GroupElement object.

This method is located on the ArcGISProject object because the container property allows you to create graphic elements in either a Layout object, a graphics layer in a Map object, or a GroupElement object in a layout or graphics layer.

You can not create a new, empty group element. Rather, you need to have existing elements to embed within the group element. If the container is a layout or graphics layer, the group will be created at the root level. If the container references an existing group element, a child group element will be created. The first element in the list will be the first element in the group, the next element in the list will appear below the first element in the contents pane, and so on.

Refer to the GroupElement class help topic for more information and code samples.

createLayout (page_width, page_height, page_units, {name})
ParameterErläuterungDatentyp
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
Rückgabewert
DatentypErläuterung
Layout

If a variable reference is optionally provided, it will represent a reference to the new Layout object.

This method returns a reference to a new Layout object. If you want to see the layout and activate it in a view, call the openView method on the Layout. The next steps will be to populate it with new layout elements using different constructor methods on the Layout class or the ArcGISProject class.

createMap ({name}, {map_type})
ParameterErläuterungDatentyp
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

(Der Standardwert ist Map)

String
Rückgabewert
DatentypErläuterung
Map

If a variable reference is specified, it will represent one of the supported map_type objects.

This method returns a reference to a new map class. If the script is run within the application, the basemap specified in the project settings will get applied. If the script is run stand-alone, the Topographic basemap will automatically get added.

createPictureElement (container, geometry, path, {name}, {lock_aspect_ratio})
ParameterErläuterungDatentyp
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.

(Der Standardwert ist True)

Boolean
Rückgabewert
DatentypErläuterung
PictureElement

If a variable is provided, it will reference the newly returned PictureElement object.

This method is located on the ArcGISProject object because the container property allows you to create graphic elements in either a Layout object, a graphics layer in a Map object, or a GroupElement object in a layout or graphics layer.

If the element is created using a point geometry, the point location will represent the anchor position and will be added at full size based on its number of pixels. Later you can resize the element using the elementWidth and elementHeight properties. If the picture is created with a non-rectangular polygon shape, the minimum envelope that encompasses all coordinates will be used instead.

Refer to the PictureElement class help topic for more information and code samples.

createPredefinedGraphicElement (container, geometry, shape_type, {style_item}, {name}, {lock_aspect_ratio})
ParameterErläuterungDatentyp
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.

(Der Standardwert ist True)

Boolean
Rückgabewert
DatentypErläuterung
GraphicElement

If a variable is provided, it will reference the newly returned GraphicElement object.

This method is located on the ArcGISProject object because the container property allows you to create graphic elements in either a Layout object, a graphics layer in a Map object, or a GroupElement object in a layout or graphics layer.

If the element is created using a point geometry, the point location will represent the anchor position and there will be a default size. Later you can resize the element using the elementWidth and elementHeight properties. The createGraphicElement method is very similar but it allows you to create custom shapes.

Refer to the GraphicElement class help topic for more information and code samples.

createTextElement (container, geometry, text_type, text, {text_size}, {font_family_name}, {font_style_name}, {style_item}, {name}, {lock_aspect_ratio})
ParameterErläuterungDatentyp
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.

Hinweis:

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.

Hinweis:

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.

(Der Standardwert ist True)

Boolean
Rückgabewert
DatentypErläuterung
TextElement

If a variable is provided, it will reference the newly returned TextElement object.

This method is located on the ArcGISProject object because the container property allows you to create group elements in a Layout object, a graphics layer in a Map object, or a GroupElement object in a layout or graphics layer.

If the text element is using a point geometry, the point location will represent the anchor position and there will be a default size. You can resize the element using the elementWidth and elementHeight properties.

See the TextElement help topic for more information and code samples.

deleteItem (project_item)
ParameterErläuterungDatentyp
project_item

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

Object

The item is permanently deleted from the project. Deleting an item may have an impact on other items. For example, if you delete a map that is used in a layout, the MapFrame that references the map will also lose the reference to the map and the map property will be set to None.

importDocument (document_path, {include_layout}, {reuse_existing_maps})
ParameterErläuterungDatentyp
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.

(Der Standardwert ist 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.

(Der Standardwert ist False)

Boolean
Rückgabewert
DatentypErläuterung
Map

When importing a map document (.mxd), if include_layout is True, it returns a reference to the layout. If include_layout is False, it returns the first map in the map document. It returns the only single map found in a globe (.3dd) or scene (.sxd) document. The corresponding layout is returned with a .pagx file and report with an .rptx file.

This method imports one document at a time. To import multiple documents, run the method once for each document. A map document (.mxd) always has a layout. While migrating map documents, if you do not want to import the layout, set include_layout=False.

listBasemaps ({wildcard})
ParameterErläuterungDatentyp
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.

(Der Standardwert ist None)

String
Rückgabewert
DatentypErläuterung
List

Returns a Python list of String objects.

The listBasemaps method returns a list object even if only one basemap is returned so use an index number to return a String instead. The output from listBasemaps can then be used in the addBasemap method on the Map class.

The following script adds a basemap to a map.


p = arcpy.mp.ArcGISProject('current')
bm = p.listBasemaps('National Geographic*')[0]
m = p.listMaps('Yosemite National Park')[0]
m.addBasemap(bm)
listBrokenDataSources ()
Rückgabewert
DatentypErläuterung
List

A Python list of Layer and/or Table objects.

The listBrokenDataSources method always returns a Python list object even if only one broken layer or table is returned.

listColorRamps ({wildcard})
ParameterErläuterungDatentyp
wildcard

A wildcard is based on the color ramp name as it appears in the application. A combination of asterisks (*) and characters can be used to help limit the resulting list.

(Der Standardwert ist None)

String
Rückgabewert
DatentypErläuterung
List

Returns a list of ColorRamp objects.

It is possible to have multiple color ramps in a project with the same name. It is important that you author your project with color ramp names that can be easily searched using a unique name. An index number can be used to return a specific color ramp. For example, the following line will return the first color ramp object in the list: cr = aprx.listColorRamps("Black*")[0].

listLayouts ({wildcard})
ParameterErläuterungDatentyp
wildcard

A wildcard is based on the layout name and is not case sensitive. A combination of asterisks (*) and characters can be used to help limit the resulting list.

(Der Standardwert ist None)

String
Rückgabewert
DatentypErläuterung
List

A Python list of Layout objects in an ArcGIS project.

Returns a Python list of Layout objects in an ArcGIS project (.aprx).

listMaps ({wildcard})
ParameterErläuterungDatentyp
wildcard

A wildcard is based on the map name and is not case sensitive. A combination of asterisks (*) and characters can be used to help limit the resulting list.

(Der Standardwert ist None)

String
Rückgabewert
DatentypErläuterung
List

A Python list of Map objects in an ArcGIS project.

Returns a Python list of Map objects in an ArcGIS project (.aprx).

listReports ({wildcard})
ParameterErläuterungDatentyp
wildcard

A wildcard is based on the report name and is not case sensitive. A combination of asterisks (*) and characters can be used to help limit the resulting list.

(Der Standardwert ist None)

String
Rückgabewert
DatentypErläuterung
List

A Python list of Report objects in an ArcGIS project.

Returns a Python list of Report objects in an ArcGIS project (.aprx).

listStyleItems (style, style_class, {wildcard})
ParameterErläuterungDatentyp
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.

Hinweis:

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.

(Der Standardwert ist 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.

(Der Standardwert ist 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.

(Der Standardwert ist None)

String
Rückgabewert
DatentypErläuterung
List

Returns a list of StyleItem objects.

It is possible to have multiple style items in a project with the same name. If that is the case, then in addition to the wildcard parameter, you can also use properties like category and tags to validate that you have the style item you want. See the code example in the StyleItem class help topic.

save ()

Saves changes to an ArcGISProject (.aprx). The project is saved and the project variable continues to reference the original ArcGISProjectobject.

saveACopy (file_name)
ParameterErläuterungDatentyp
file_name

A string used to save an ArcGISProject (.aprx) to a new file path or file name.

String

The method creates a new output project file, but the project variable continues to reference the original ArcGISProject object. It does not duplicate all the content within a project folder.

updateConnectionProperties (current_connection_info, new_connection_info, {auto_update_joins_and_relates}, {validate}, {ignore_case})
ParameterErläuterungDatentyp
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.

(Der Standardwert ist 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.

(Der Standardwert ist 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.

(Der Standardwert ist False)

Boolean

For more detailed discussion, parameter information, scenarios, and code samples, see Updating and fixing data sources.

updateDatabases (databases, {validate})
ParameterErläuterungDatentyp
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.
    Hinweis:

    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.

(Der Standardwert ist True)

Boolean
Rückgabewert
DatentypErläuterung
List

A list of invalid databases.

To update a project's databases, you must set the entire list of databases at once. You cannot add, remove, or update a single database at a time. You can either build a new list from scratch or you can modify the list returned by the databases property and push the entire list back to the project using the updateDatabases method.

updateFolderConnections (folder_connections, {validate})
ParameterErläuterungDatentyp
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.
    Hinweis:

    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.

(Der Standardwert ist True)

Boolean
Rückgabewert
DatentypErläuterung
List

A list of folders that do not have valid connections.

To update a project's folder connections, you must set the entire list of databases at once. You cannot add, remove, or update a single folder connection at a time. You can either build a new list from scratch or you can modify the list returned by the folderConnections property and push the entire list back to the project using the updateFolderConnections method.

Codebeispiel

ArcGISProject example 1

The following script demonstrates how to import documents into an existing ArcGIS Pro template project. It also sets up some of the default project settings and saves the result to a new project file.

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 example 2

The following script prints the names of objects in a project . It uses the keyword CURRENT, so it should be run from the Python window. The script prints the name of each map followed by its list of layers. Then it prints the name of each layout along with page size information.

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 example 3

The following script uses the keyword CURRENT, so it should be run from the Python window. The script copies an existing map, adds a new layer to it, sets the map's default camera property that controls the extent of newly opened views, exports the map view to PDF, and removes the newly created map from the project.

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 example 4

The following script iterates though all file geodatabase layers in a project and adds each unique workspace path to the Folders project item folder.

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 example 5

The following script appends new file geodatabases to the Databases project item folder providing quick access to the data from the project.

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 example 6

The following script creates a layout in a project and creates predefined graphic elements using a referenced system style. A function is used to create the envelope for each graphic rectangle added to the layout.

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 example 7

The following script creates a map with a graphics layer. Next it adds two pictures to a new group layer within the graphics layer. A function is used to create the envelope for each picture and they are offset by 3000000 map units.

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