Zusammenfassung
Provides access to map document (.mxd) properties and methods. A reference to this object is essential for most map scripting operations.
Auswertung
The MapDocument object is usually one of the first object references created in a map automation script because it is a required parameter for many of the arcpy.mapping functions. It is through the MapDocument object that you ultimately can get access to almost all other objects within a map document (for example, data frames, layers, page layout elements). The MapDocument object provides access to most of the map document properties found in the Map Document Properties dialog box in ArcMap (File > Map Document Properties). The object also contains methods for managing map document thumbnails and methods for saving map documents that are found within the ArcMap File menu.
There are two different ways that a MapDocument object can be created using the MapDocument function. The first, and most recommended, method is to provide a system path to the location of the map document (.mxd) on disk. This technique is most versatile because then a script can be run outside an ArcGIS application. Referencing a specific map document on disk provides more control in terms of how the script will execute because a given script may not work on all map documents.
The second technique is to use the CURRENT keyword as an input parameter to the MapDocument function. This technique only works from within an ArcMap application because the MapDocument object references the map document that is currently loaded into the ArcMap application. Using CURRENT is very helpful when quickly testing and learning the scripting capabilities and command syntax within the Python window. You may start off learning the syntax in the Python window, then start pasting those lines of code into a more permanent script saved to disk.
Script tools that use the CURRENT keyword must be run from within ArcMap (either from a custom menu or the Catalog window). Script tools using CURRENT will not execute properly if run from within the ArcCatalog application. For this same reason, if a script tool has a validation script that includes a reference to CURRENT, an error may occur if you try to edit the validation script from ArcCatalog. Be sure to edit the script tool's validation code from within the ArcMap Catalog window.
To use the CURRENT keyword within a script tool, background processing must be disabled. Background processing runs all scripts as though they were being run as stand-alone scripts outside an ArcGIS application, and for this reason, CURRENT will not work with background processing enabled. There is a new script tool option called Always run in foreground that ensures that a script tool will run in the foreground even if background processing is enabled.
It is very important to understand how variables reference MapDocument objects in the scripting environment, especially when you are saving your results to a new file. You must understand that when you initially create a variable that references a MapDocument object, it will always point to the original map document on disk or currently in memory (via CURRENT). In the ArcMap application, if you perform a SaveAs to a new file location, all subsequent changes are directed to the new file. This is not possible within the scripting environment, and therefore, a saveAs method is not provided. The MapDocument class has save and saveACopy methods for managing modifications to a map document.
If scripting is used to modify the appearance of some map document elements while using the CURRENT map document (for example, change a layer name, the data frame extent, and so on), the map may not automatically update with each executed line of code. To refresh the map document to reflect the changes, use either the RefreshActiveView or RefreshTOC functions. These functions will refresh the map display or page layout and table of contents, respectively. The refresh functions are only needed if you want to see the application updated. Arcpy.mapping export, save, and printing functions will generate the expected updated results without using these functions.
Some layers within a map document or layer file may be password protected because the user and password information is not saved within the layer file or map document. Map documents that contain these layers will prompt the user to enter the appropriate information while the document is opening. The arcpy.mapping scripting environment will by default suppress these dialog boxes during execution, but that means that the layers will be treated as though they have broken data sources. In other words, secured layers will not be rendered in any output. If it is necessary for these layers to render appropriately, then there are a couple of options. First, save the user name and password information with the layers. Second, the CreateDatabaseConnection geoprocessing function allows you to create a connection that persists in memory. If this command is used prior to opening a map document (.mxd) with the MapDocument function or a layer file with the Layer function, then SDE layers will render. Currently, there is not an alternative for secured Web services.
The variable that references the MapDocument object will place a lock on the map document file. It is good practice to remove the Map Document object reference using the Python del command at the end of a script or within a try/except statement.
Changing data sources in a map document is a common requirement. There are two methods on the MapDocument object that help with this. The findAndReplaceWorkspacePaths method is intended for replacing part or all of a layer's or table's workspace path. The replaceWorkspaces method allows you to change not only a path but also the workspace type. For more detailed discussion, parameter information, scenarios, and code samples, please refer to the Updating and fixing data sources with arcpy.mapping help topic.
Syntax
MapDocument (mxd_path)
Parameter | Erklärung | Datentyp |
mxd_path | A string that includes the full path and file name of an existing map document (.mxd) or a string that contains the keyword CURRENT. | String |
Eigenschaften
Eigenschaft | Erklärung | Datentyp |
activeDataFrame (Nur lesen) | Returns a DataFrame object that represents the currently active data frame in a map document (.mxd). The activeDataFrame property will return the appropriate data frame even if the map document is in page layout view. If you want to set the active data frame, use the activeView property. | DataFrame |
activeView (Lesen und schreiben) | Provides the ability to set or get a map document's active view to either a single data frame or the page layout. The property works with a string that represents the active data frame name or the PAGE_LAYOUT keyword. If activeView is set to PAGE_LAYOUT and the map document is saved, the next time the map document is opened, it will be opened in layout mode. If activeView is set to a data frame name and the map document is saved, the next time the map document is opened, it will be opened in data view, and that particular data frame will be the active data frame. | String |
author (Lesen und schreiben) | Provides the ability to either get or set the map document's author information. | String |
credits (Lesen und schreiben) | Provides the ability to either get or set the map document's credits or copyright information. | String |
dataDrivenPages (Nur lesen) | Returns a DataDrivenPages object that can then be used to manage the pages in a Data Driven Pages enabled map document. | DataDrivenPages |
dateExported (Nur lesen) | Returns a Python datetime object that reports the date the last time the map document was exported. This value is only current if the map document was saved after the map was exported. | DateTime |
datePrinted (Nur lesen) | Returns a Python datetime object that reports the date the last time the map document was printed. This value is only current if the map document was saved after the map was printed. | DateTime |
dateSaved (Nur lesen) | Returns a Python datetime object that reports the date the last time the map document was saved. | DateTime |
description (Lesen und schreiben) | Provides the ability to either get or set the map document's description information. | String |
filePath (Nur lesen) | Returns a string value that reports the fully qualified map document path and file name. | String |
hyperlinkBase (Lesen und schreiben) | Provides the ability to either get or set the base path or URL used for field-based hyperlinks to documents or URLs. | String |
isDDPEnabled (Nur lesen) | Returns True if the map document is Data Driven Pages enabled. | Boolean |
pageSize (Nur lesen) | Provides the ability to get the layout's page size. It returns a named tuple with the properties width and height. The following script shows a few different techniques to print a map document's page width and height.
| tuple |
relativePaths (Lesen und schreiben) | Provides the ability to control if a map document stores relative paths to the data sources. A value of True sets relative paths; a value of False sets full paths to the data sources. | Boolean |
summary (Lesen und schreiben) | Provides the ability to either get or set the map document's summary information. | String |
tags (Lesen und schreiben) | Provides the ability to either get or set the map document's tag information. Separate tags with a single comma (,). | String |
title (Lesen und schreiben) | Provides the ability to either get or set the map document's title information. | String |
Methodenübersicht
Methode | Erklärung |
deleteThumbnail () | Deletes a map document's (.mxd) thumbnail image |
findAndReplaceWorkspacePaths (find_workspace_path, replace_workspace_path, {validate}) | Finds old workspace paths and replaces them with new paths for all layers and tables in a map document (.mxd) |
makeThumbnail () | Creates a map document's (.mxd) thumbnail image |
replaceWorkspaces (old_workspace_path, old_workspace_type, new_workspace_path, new_workspace_type, {validate}) | Replaces an old workspace with a new workspace for all layers and tables in a map document (.mxd); also provides the ability to switch workspace types (for example, replace a file geodatabase data source with an SDE data source). |
save () | Saves a map document (.mxd) |
saveACopy (file_name, {version}) | Provides an option to save a map document (.mxd) to a new file, and optionally, to a previous version. |
Methoden
deleteThumbnail ()
This performs the same operation as clicking the Delete Thumbnail button on the File > Map Document Properties dialog box in ArcMap.
findAndReplaceWorkspacePaths (find_workspace_path, replace_workspace_path, {validate})
Parameter | Erklärung | Datentyp |
find_workspace_path | A string that represents the workspace path or connection file you want to find. If an empty string is passed, then all workspace paths will be replaced with the replace_workspace_path, depending on the value of the validate parameter. | String |
replace_workspace_path | A string that represents the workspace path or connection file you want to use to replace. | String |
validate | If set to True, a workspace will only be updated if the replace_workspace_path value is a valid workspace. If it is not valid, the workspace will not be replaced. If set to False, the method will set all workspaces to match the replace_workspace_path, regardless of a valid match. In this case, if a match does not exist, then the layer and table's data sources would be broken. (Der Standardwert ist True) | Boolean |
For more detailed discussion, parameter information, scenarios, and code samples, please refer to the Updating and Fixing Data Sources with arcpy.mapping help topic.
makeThumbnail ()
This performs the same operation as clicking the Make Thumbnail button in the File > Map Document Properties dialog box in ArcMap.
replaceWorkspaces (old_workspace_path, old_workspace_type, new_workspace_path, new_workspace_type, {validate})
Parameter | Erklärung | Datentyp |
old_workspace_path | A string that represents the workspace path or connection file you want to find. If an empty string is passed, then all workspace paths will be replaced with the new_workspace_path, depending on the value of the validate parameter. | String |
old_workspace_type | A string keyword that represents the workspace type of the old data to be replaced. If an empty string is passed, multiple workspaces can be redirected into one workspace.
| String |
new_workspace_path | A string that represents the new workspace path or connection file. | String |
new_workspace_type | A string keyword that represents the workspace type that will replace the old_workspace_type.
| String |
validate | If set to True, a workspace will only be updated if the new_workspace_path value is a valid workspace. If it is not valid, the workspace will not be replaced. If set to False, the method will set all workspaces to match the new_workspace_path, regardless of a valid match. In this case, if a match does not exist, then the data sources would be broken. (Der Standardwert ist True) | Boolean |
For more detailed discussion, parameter information, scenarios, and code samples, please refer to the Updating and Fixing Data Sources with arcpy.mapping help topic.
save ()
This performs the same operation as File > Save in ArcMap.
saveACopy (file_name, {version})
Parameter | Erklärung | Datentyp |
file_name | A string that includes the location and name of the output map document (.mxd). | String |
version | A string that sets the output version number. The default value will use the current version.
(Der Standardwert ist None) | String |
This performs the same operation as File > SaveACopy in ArcMap. Features that are not supported in prior versions of the software will be removed from the newly saved map document. When calling saveACopy in a stand-alone script, document bloat will not get removed. This is because stand-alone Python scripts access a map document differently that if run from within the application.
Codebeispiel
MapDocument example 1
The following script creates a separate MXD file for each data frame in a map document. The output map documents will be saved in data view mode so when each map document is opened, the corresponding data frame will be active data frame. The script also sets the title property of each output map document. Because this script uses a system path to the map document, it can be executed outside an ArcMap application. Note: Python strings cannot end with a backslash, even when the string is preceded by an r. You must use a double backslash. This becomes important when appending dynamic file names to a folder path.
import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Project\Project.mxd")
for df in arcpy.mapping.ListDataFrames(mxd):
mxd.activeView = df.name
mxd.title = df.name
mxd.saveACopy(r"C:\Project\Output\\" + df.name + ".mxd")
del mxd
MapDocument example 2
The following script demonstrates how the CURRENT keyword can be used within the Python window. This sample will update the first data frame's name and refresh the table of contents so the change can be see in the application. Paste the following code into the Python window within a new ArcMap document.
mxd = arcpy.mapping.MapDocument("CURRENT")
arcpy.mapping.ListDataFrames(mxd)[0].name = "New Data Frame Name"
arcpy.RefreshTOC()
del mxd
>>> mxd = arcpy.mapping.MapDocument("CURRENT")
... arcpy.mapping.ListDataFrames(mxd)[0].name = "New Data Frame Name"
... arcpy.RefreshTOC()
... del mxd
...
MapDocument example 3
The following is another simple script that demonstrates the use of the CURRENT keyword within the Python window. Each layer name will be printed to the Python window. Loops are also possible, provided that you maintain the correct indentation. Similar to the example above, paste the code below into the Python window.
mxd = arcpy.mapping.MapDocument("CURRENT")
for lyr in arcpy.mapping.ListLayers(mxd):
print lyr.name
del mxd
>>> mxd = arcpy.mapping.MapDocument("CURRENT")
... for lyr in arcpy.mapping.ListLayers(mxd):
... print lyr.name
... del mxd
...
MapDocument example 4
The following script will allow secured layers to render correctly by creating an SDE connection in memory before opening a map document that requires password information. This script simply defines the connection information and exports the map document to a PDF file. It is good practice to delete this reference from memory before the script closes.
import arcpy, os
#Remove temporary connection file if it already exists
sdeFile = r"C:\Project\Output\TempSDEConnectionFile.sde"
if os.path.exists(sdeFile):
os.remove(sdeFile)
#Create temporary connection file in memory
arcpy.CreateArcSDEConnectionFile_management(r"C:\Project\Output", "TempConnection", "myServerName", "5151", "myDatabase", "DATABASE_AUTH", "myUserName", "myPassword", "SAVE_USERNAME", "myUser.DEFAULT", "SAVE_VERSION")
#Export a map document to verify that secured layers are present
mxd = arcpy.mapping.MapDocument(r"C:\Project\SDEdata.mxd")
arcpy.mapping.ExportToPDF(mxd, r"C:\Project\output\SDEdata.pdf")
os.remove(sdeFile)
del mxd