MapDocument (arcpy.mapping)

Summary

Provides access to map document (.mxd) properties and methods. A reference to this object is essential for most map scripting operations.

Discussion

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

Explanation

Data Type

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

Properties

Property

Explanation

Data Type

activeDataFrame

(Read Only)

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.

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

(Read and Write)

Provides the ability to either get or set the map document's author information.

String

credits

(Read and Write)

Provides the ability to either get or set the map document's credits or copyright information.

String

dataDrivenPages

(Read Only)

Returns a DataDrivenPages object that can then be used to manage the pages in a Data Driven Pages enabled map document.

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.

Methods

deleteThumbnail ()

This performs the same operation as clicking the Delete Thumbnail button on the File > Map Document Properties dialog box in ArcMap.

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.

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.

ACCESS_WORKSPACE — A personal geodatabase or Access workspace

ARCINFO_WORKSPACE — An ArcInfo coverage workspace

CAD_WORKSPACE —A CAD file workspace

EXCEL_WORKSPACE —An Excel file workspace

FILEGDB_WORKSPACE —A file geodatabase workspace

NONE —Used to skip the parameter

OLEDB_WORKSPACE —An OLE database workspace

PCCOVERAGE_WORKSPACE —A PC ARC/INFO Coverage workspace

RASTER_WORKSPACE —A raster workspace

SDE_WORKSPACE —An SDE geodatabase workspace

SHAPEFILE_WORKSPACE —A shapefile workspace

TEXT_WORKSPACE —A text file workspace

TIN_WORKSPACE —A TIN workspace

VPF_WORKSPACE —A VPF 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.

ACCESS_WORKSPACE — A personal geodatabase or Access workspace

ARCINFO_WORKSPACE — An ArcInfo coverage workspace

CAD_WORKSPACE —A CAD file workspace

EXCEL_WORKSPACE —An Excel file workspace

FILEGDB_WORKSPACE —A file geodatabase workspace

OLEDB_WORKSPACE —An OLE database workspace

PCCOVERAGE_WORKSPACE —A PC ARC/INFO Coverage workspace

RASTER_WORKSPACE —A raster workspace

SDE_WORKSPACE —An SDE geodatabase workspace

SHAPEFILE_WORKSPACE —A shapefile workspace

TEXT_WORKSPACE —A text file workspace

TIN_WORKSPACE —A TIN workspace

VPF_WORKSPACE —A VPF workspace

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.

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.

10.1 —Version 10.1

10.0 —Version 10.0

8.3 —Version 8.3

9.0 —Version 9.0/9.1

9.2 —Version 9.2

9.3 —Version 9.3

(The default value is 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.

Code Sample

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.

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.

When pasted into the interactive window it will appear as follows. The three dots to the left of the code block indicate that the lines are a single block of code that will be executed together. You must press the Enter key to execute these lines.

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.

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.

importarcpy,os#Remove temporary connection file if it already existssdeFile=r"C:\Project\Output\TempSDEConnectionFile.sde"ifos.path.exists(sdeFile):os.remove(sdeFile)#Create temporary connection file in memoryarcpy.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 presentmxd=arcpy.mapping.MapDocument(r"C:\Project\SDEdata.mxd")arcpy.mapping.ExportToPDF(mxd,r"C:\Project\output\SDEdata.pdf")os.remove(sdeFile)delmxd