Tutorial: Getting started with arcpy.mp

Complejidad: PrincipianteRequisitos de datos: Usar datos propios Objetivo: The goal of this tutorial is to introduce you to the basics of arcpy.mp. You will use Python to connect to a project, reference project items, and export a layout to PDF.

This tutorial walks you through some common arcpy.mp workflows and introduces some important concepts along the way. It is aimed to help users who are new to Python scripting and arcpy.mp. The steps are generic enough to work with any data and all license levels.

Nota:

The steps below present a high-level overview of arcpy.mp. Throughout the tutorial, there are links to detailed help topics that provide more information about the concepts involved, and in nearly all cases, the topics include additional sample snippets of code.

Tutorial setup

You need to set up a basic project that contains a single map and a layout.

  1. Open a new, blank project.
  2. On the Insert tab, in the Project group, click New Map and choose New Map again from the drop-down menu.
  3. Make sure the map name is Map. You will reference it by this name later in the tutorial.
  4. On the Insert tab, click New Layout and select a layout from the gallery.
  5. Make sure the layout name is Layout. You will reference it by this name later in the tutorial.
  6. On the Insert tab, in the Map Frames group, choose a map from your project in the map frames drop-down menu and add it to the layout.
  7. On the Project tab, click Save.

Python window

The easiest place to start learning arcpy.mp is in the Python window. It allows you to perform small Python-based workflows and work through concepts directly in the application before being refined in larger scripts. The Python window is part of the ArcGIS Pro application framework and provides intelliSense, autocompletion, and command syntax so you can quickly enter the appropriate parameter information in the correct order.

  1. On the Analysis tab, click Python.
  2. By default, the Python window appears docked at the bottom of the application.

  3. Click in the code pane where it says Enter Python code here.
  4. A blinking pointer appears where you can type code.

Reference an existing project

Typically, one of the first operations you do with an arcpy.mp script is reference an existing project () or layer file (.lyrx or .lyr) that you want to work with. In this section, you'll reference a project.

There are two ways to reference a project. The first is to reference it on disk by providing a path to the .aprx file. If you are building a script that is to be run outside the ArcGIS environment, you must reference a project using its full system path. The second way is to reference the project that is currently loaded into the ArcGIS Pro application. When working in the Python window, it is convenient to reference the currently loaded project because changes made to it can be seen directly in the application. The following steps reference a project currently loaded into ArcGIS Pro.

  1. In the Python window, type the following line of code and press Enter. Keep in mind that Python syntax is case sensitive.
  2. >>> aprx = arcpy.mp.ArcGISProject("CURRENT")
    The ArcGISProject function returns an ArcGISProject object reference to a variable called aprx. The string is a keyword used to reference the currently loaded project. In place of CURRENT, you could also provide a path to the project file (.aprx).
  3. In the Python window, type the following:
  4. >>> aprx.
    After typing the dot, you'll see a long list of methods and properties available to the ArcGISProject object.
  5. In the Python window, continue to type the following and press Enter. You will need to provide your own path to an existing geodatabase.
  6. >>> aprx.defaultGeodatabase = r"path to a geodatabase of yours"  #### for example, aprx.defaultGeodatabase = r"C:\Projects\YosemiteNP\Data\Yosemite.gdb")
    By default, when a new project is created, its default geodatabase is set to an empty geodatabase created with the same name as your project and in the same folder location. You just changed the location to an existing geodatabase.
    Notice how the path has a lowercase r in front of the string. This is a special character in Python that stands for raw. It means to interpret the string as it is and to ignore any other special characters within the string. The lowercase r is used because the path has backslashes within the string. Backslashes in Python are also special characters. For example, \t within a string is converted to a tab, and \n is converted to a new line. In the example above, you don't want special characters to be used; you want the raw, literal string. There are two other equivalent ways to type the same path in Python. First, use forward slashes (for example, "C:/Project/States.lyr"). Python works well with forward slashes; they are a cross-platform standard. Second, use double backslashes (for example, "C:\\Project\\Lakes.lyr"). The first backslash cancels out the second. The lowercase r technique is important to remember because, when you copy system paths on a Windows platform, backslashes are included.
  7. To see the change you just made to the project, click the Project tab and select Options.
  8. The first panel displays the change you made for the default geodatabase.
  9. Click Cancel.
  10. In the Python window, type the following and press Enter:
  11. >>> aprx.save()

    Check the timestamp on the file. It should be updated to the current date and time.

    The save() method does not have any parameters, but because it is a method, you must include the parentheses. To verify the location where the project was saved, do the following:
  12. In the Python window, type the following and press Enter:
  13. >>> print(aprx.filePath)
    Your project path is printed to the code pane.

Add a layer file to the map

Now that you have a reference to a project, add a layer file (.lyr or .lyrx) to the map. First, reference the map in the project and reference a layer file on disk; finally, add the layer file to the map.

Nota:
For the following steps, locate an existing layer file. If you don't have one, you need to author one.

  1. In the Python window, type the following:
  2. >>> m = aprx.listMaps("Map")[0]
    All ArcPy List functions return Python List objects. The items returned in the list are zero based, meaning that the first item in the list has an index value of 0 and the second is 1, all the way to n-1. Because you want the m variable to reference a Map object and not a Python List object, you must append an index number after the function. Appending a [0] at the end of the function returns the first map in the list. In this case, it should be the only map in the list, because you also provided the name of the map as a wildcard parameter. If you uniquely name your maps in the project and use the appropriate wildcard value to isolate the item, you should always return a list with only one item, and index [0] will work.
    Next, you need to reference a layer file before you can use the addLayer method. The process of referencing a layer file is identical to referencing a project, except you use the addLayer method on the Map object rather than the ArcGISProject function.
  3. In the Python window, type the following:
  4. >>> m.addLayer(
    The autocompletion shows that there is one required parameter named add_layer_or_layerfile and one optional parameter (surrounded by { } brackets) named add_position. The first parameter can reference an existing layer in the project or in a layer file. The second parameter is optional and controls the placement of the layer in the table of contents.
    Before you can add the layer, you need to reference the layer file you want to add.
  5. In the Python window, backspace to remove the addLayer method, type the following, and press Enter:
  6. >>> lyrFile = arcpy.mp.LayerFile(r"path to a layer file")  ### for example, lyrFile = arcpy.mp.LayerFile(r"C:\Projects\YosemiteNP\LYRS\rivers.lyrx")
    In the step above, a reference to an existing layer file was created, and that reference is stored in a variable named lyrFile.
  7. In the Python window, type the following and press Enter:
  8. >>> m.addLayer(lyrFile, "TOP")
    Your layer is added to the map. It will also appear in the layout because the map is associated with the map frame in the layout.

Export a layout to PDF

Exporting a layout to PDF only requires a couple lines of code. First, reference the layout you want to export and call the exportToPDF method.

  1. In the Python window, type the following and press Enter:
  2. >>> lyt = aprx.listLayouts("Layout")[0]
    The lyt variable references the first layout in the project named Layout. In this case, it is the only layout in the project, so it was not necessary to provide the layout name for the wildcard parameter. It is good practice to always provide the name, however. For example, you could type the following:
    >>> lyt = aprx.listLayouts()[0]
    This would work just the same. If you insert additional layouts into the project, you wouldn't be sure which layout was being exported. If you provide the name, you would be sure.
  3. In the Python window, type the following and press Enter. The path you provide will most likely be different than the example below.
  4. >>> lyt.exportToPDF(r"C:\Projects\YosemiteNP\Output\Page1.pdf")
    Check to see that your PDF file was created at the location you specified.

You have completed a common workflow using arcpy.mp. The next step is to apply this workflow to your own projects and layers. Also explore the arcpy.mp help topics. There are dozens of small code samples at the end of each topic that can be easily copied and pasted into the Python window.

Temas relacionados