Run geoprocessing tools with Python

Open a project and review datasets

Before you begin using Python to run geoprocessing tools, you will download the datasets, open a new project, and review the datasets to be used.

  1. Download the tutorial data and extract the contents to a location on your computer.

    The .zip file contains a folder named PythonGP.

    In this tutorial, the data is shown at C:\Lessons\PythonGP\. You can use a different folder, but be sure to adjust the paths in the instructions that follow.

  2. Start ArcGIS Pro.
  3. In ArcGIS Pro, next to Recent Projects, click Open another project.

    Open another project.

  4. In the Open Project window, browse to the folder you extracted from the PythonGP.zip file, click Python Geoprocessing.aprx to select it, and click OK.

    The project opens. The current map shows the boundary of the city of Toronto in Canada. You will add several feature classes to this map.

  5. If the Catalog pane is not visible, click the View tab and click Catalog Pane.
  6. Dock the Catalog pane to the right of the map.
  7. In the Catalog pane, expand Folders and expand PythonGP.
  8. Expand the Toronto.gdb file geodatabase.

    Toronto geodatabase expanded to show feature classes.

    The geodatabase contains several feature classes.

  9. Right-click the ambulances feature class and click Add To Current Map.

    This feature class represents the ambulance dispatch locations in Toronto.

  10. Add the fire_stations and communities feature classes to the same map.

    These feature classes represent the fire station and community boundaries within the city of Toronto, respectively. In this tutorial, you will run geoprocessing tools on these feature classes using Python.

  11. The Toronto.gdb geodatabase is the default geodatabase for the project. The PythonGP folder also contains a geodatabase called Results.gdb, which is currently empty but will be used to store the outputs of some of the geoprocessing tools.

Run a tool in the Python window

One of the ways to run Python in ArcGIS Pro is the Python window. It is a good way to get started writing Python code because it gives you some syntax hints.

  1. On the ribbon, click the Analysis tab, and in the Geoprocessing section, click the drop-down arrow to the right of the Python button and click Python Window.

    Open the Python window in ArcGIS Pro.

    Clicking the Python button directly opens a Python Notebook. This is another way to write Python code, but in this tutorial, the Python window will be used. See the Get started with notebooks in ArcGIS Pro tutorial to learn about using notebooks.

    The Python window contains two sections. The top section is called the transcript and the bottom section is called the prompt. You type code into the prompt section and the transcript section will display code that has been run plus any messages, such as printed results or error messages.

  2. Type the following code in the prompt section of the Python window and press Enter:

    import arcpy

    Import the

    This line of code imports the ArcPy package. ArcPy is a Python package that makes much of the functionality of ArcGIS Pro available from within Python, including geoprocessing.

    Note:

    Since you are using the Python window inside ArcGIS Pro, you can run geoprocessing tools without first importing ArcPy. However, it is considered good practice to always use import arcpy at the top of your code to ensure the same code works outside of ArcGIS Pro.

    The first tool you will use is the Add XY Coordinates tool. You'll open the attribute table of a feature class to see the results of running the tool.

  3. In the Contents pane, right-click the ambulances layer and click Attribute table.
  4. Organize the ArcGIS Pro interface so you can easily view the map, the attribute table of the ambulances layer, and the Python window.

    Exactly how you organize the interface is a matter of preference, but it is common to have maps and tables at the top and the Python window below.

  5. Type the following code in the prompt section of the Python window and press Enter:

    arcpy.management.AddXY("ambulances")

    Type the code to add XY fields to the ambulances feature class.

    When you press Enter, the code runs and the POINT_X and POINT_Y fields are added to the attribute table of the ambulances feature class.

    X and Y coordinates added to the table.

    Running the line of code runs the Add XY Coordinates tool, just like running the tool from its tool dialog box. The code you ran now appears in the transcript section of the Python window, and the results of running the tool appear below. In this case, the tool does not produce a new feature class but updates the attribute table of the existing feature class. The result that is returned from the tool is a reference to the existing ambulances feature layer in the current map.

    The line of code arcpy.management.AddXY("ambulances") has several distinct parts. The first, arcpy, is the ArcPy module, which makes it possible to use much of the functionality of ArcGIS Pro in Python, including nearly all geoprocessing tools. The next element, management, is the toolbox alias of the Data Management toolbox where the Add XY Coordinates tool resides. The next element is AddXY, which is the name of the ArcPy function that is equivalent to the Add XY Coordinates tool in ArcGIS Pro.

    The parts are separated by dots, which is called dot notation in Python, and there are no spaces. While the name of the tool is Add XY Coordinates in ArcGIS, the name of the function in ArcPy is AddXY, without spaces. Function names are sometimes identical to the tool name, but some function names are a shortened version, like this. Python function names do not have spaces in them. Since this is a function of ArcPy, it is followed by parentheses (). Both an opening and closing parenthesis are required. Within the parentheses are the parameters of the function—these are the same as the parameters of the tool when using the tool dialog box.

    In the case of the Add XY Coordinates tool, the parameters consist only of the name of a single input feature class.

    There is an alternative way to write the syntax to run tools. You will see code examples written both ways, so it is useful to know both.

  6. Type the following code in the prompt section of the Python window and press Enter:

    arcpy.AddXY_management("ambulances")

    Running the line of code runs the Add XY tool again. You won’t see any differences in the result since the previous results are overwritten.

    The two notations can be used interchangeably:

    arcpy.<toolboxalias>.<toolname>
    arcpy.<toolname>_<toolboxalias>

    The second notation uses an underscore, not a dot. This means that arcpy.<toolname>.<toolboxalias> is incorrect and will produce an error.

  7. Type the following code in the prompt section of the Python window and press Enter:

    arcpy.AddXY.management("ambulances")

    This produces an error because the AddXY function cannot be found using this notation.

    Syntax error

    The Python window has several built-in features to assist you in writing error-free code.

  8. Type the following code and pause at the dot:

    arcpy.

    When you pause after the dot, a long list of suggestions appears, in alphabetical order. These are called code autocompletion prompts.

    Code autocompletion prompts

    You can scroll through the list or continue typing characters. As you type, the list of suggestions will update accordingly.

  9. Continue typing:

    arcpy.man

    This limits the list to code elements that are part of ArcPy that start with the letters 'man'.

    Code autocompletion prompts limited to man.

  10. Hover over the entry management.

    This shows a small pop-up with the full name of the toolbox.

    Code autocompletion prompts limited to man and toolbox name.

  11. Click management in the list.

    This adds the toolbox alias followed by a dot:

    arcpy.management.

  12. Type the letter a and scroll through the list to AddXY, then click AddXY() management.

    Click AddXY.

    This adds the name of the tool, and automatically adds a pair of parentheses:

    Prompts for input features

    With the pointer between the parentheses, a pop-up appears with the names of the two point feature classes on the map. Below the line of code is a pop-up with a brief explanation of the tool. This includes the tool syntax, which is:

    management.AddXY(in_features)

    This is similar to the syntax you will find in the help pages for the tool. It is convenient to see the syntax as you are typing your code. There is also a brief explanation of the first (and only) tool parameter.

    Above the line of code is a pop-up with a suggestion for the value for the first tool parameter. The input features for the tool can only consist of point features. The suggested values consist of all the point feature layers in the open map. In this example, the point feature layers are ambulances and fire_stations. The data layer communities does not appear since it is a polygon feature layer. These code autocompletion prompts assist you with writing correct code since they only show the input features that are meaningful.

  13. Click the fire_stations entry in the pop-up.

    Other syntax GP

    This adds the name of the feature layer to the line of code, and automatically adds quotes.

    arcpy.management.AddXY('fire_stations')

    Tip:
    If you move your pointer away from the Python window, the pop-ups disappear. To bring them back, first place your pointer in the line of code anywhere outside of the parentheses, then place your pointer back inside the parentheses.

    The line of code is now complete.

  14. Press Enter to run the line of code.
  15. In the Contents pane, right-click the fire_stations layer and click Attribute table.

    The POINT_X and POINT_Y fields have been added to the feature class.

    Fire stations now have coordinates.

  16. Close the attribute table.

Next, you will use code autocompletion prompts to get the correct syntax for geoprocessing tools that use more complex tool parameters.

Understand tool parameters

The Add XY Coordinates tool only uses a single parameter, which results in very short code. Most geoprocessing tools have more parameters, including both required and optional ones. You will look at the Buffer tool as an example of a tool with more tool parameters.

You will start by reviewing the tool’s syntax on the help page.

  1. Browse to the following URL:
  2. Scroll down to the Parameters section. and click the Dialog tab.

    Buffer tool help parameters

    This table provides a detailed explanation of the tool parameters, including their data type. A good familiarity with the tool parameters makes it easier to use the tool in Python code.

  3. Click the Python tab.

    Buffer tool help parameters for Python

    This shows the syntax for the Buffer tool in Python. The Buffer tool is located in the Analysis Tools toolbox, so the code starts with arcpy.analysis. In parentheses are the parameters of the Buffer tool. These are identical to the parameters on the tool dialog box, in the same order. Each parameter is given a name (for example, in_features), and the parameters are separated by a comma, followed by a space. Parameter naming follows the conventions for variable names in Python: lowercase only with words separated by an underscore for legibility.

    Geoprocessing tools have required and optional parameters. Required parameters come before optional parameters. In the syntax, you can recognize optional parameters by the use of braces { }. By reading the syntax, you can determine that the Buffer tool has three required parameters, followed by five optional parameters.

    When a tool parameter is optional, this means there is a default value. If you do not specify a value for an optional parameter, the default will be used.

    You will first run the Buffer tool using only the required parameters.

  4. In ArcGIS Pro, in the Python Window, type the following code in the prompt section:

    arcpy.Buf

  5. Click the Buffer() analysis entry in the pop-up list.

    Type arcpy.Buff, then click Buffer() analysis.

    You can also use the Up and Down arrows on the keyboard to highlight items on the list. When an entry is highlighted, press the Tab key to add the item.

    The autocompletion prompt is Buffer_analysis, but the code is added using this syntax:

    arcpy.analysis.Buffer()

    Recall that arcpy.analysis.Buffer() and arcpy.Buffer_analysis() are different ways of referring to the same tool. Both are correct.

    With the pointer inside the parentheses, the tool’s syntax appears below, and the suggested feature layers for the first parameter appear above.

    Buffer syntax pop-up

    The first parameter of the Buffer tool is called in_features. This parameter is shown in bold in the syntax pop-up. An explanation of this parameter is shown below. This display will update as you complete the tool parameters.

  6. In the pop-up, click fire_stations.

    This adds the name of the feature layer to the line of code, and automatically adds quotes.

    arcpy.analysis.Buffer('fire_stations')

  7. Next, type a comma followed by a space.

    arcpy.analysis.Buffer('fire_stations', )

    Output features in syntax prompt.

    In the syntax pop-up, the next parameter, out_feature_class, is now shown in bold. No suggestions are provided for the name, since this is an output.

  8. Type 'fire_buffer' within quotes for the out_feature_class name.

    the line of code is now:

    arcpy.analysis.Buffer('fire_stations', 'fire_buffer')

    You can use single or double quotes when writing the name of a feature class. When selecting from a list of suggested feature layers, the autocompletion prompts favor single quotes, but you can switch between the two styles of quotes in a single line of code, as long as you consistently surround each string with the same quote. For example, the following is correct:

    arcpy.analysis.Buffer('fire_stations', "fire_buffer")

    But the following is not correct and produces a syntax error:

    arcpy.analysis.Buffer('fire_stations', 'fire_buffer")

  9. Change the last single quote to a double quote.

    Highlighted error quote mismatch

    The second tool parameter is shown in orange highlighting, which indicates a syntax error. This is helpful since you know this line of code will result in an error even before you try running it.

  10. Change the double quote back to a single quote.
  11. Next, type a comma followed by a space.

    Buffer distance or field syntax hint

    The third parameter is the distance to be used in the creation of buffers. This can be a value you enter or a field in the attribute table of the input features. The code autocompletion suggestions show the fields of the fire_stations feature layer. In this case, however, you will type a numeric value.

  12. Type "1000 meters" including the quotes.

    arcpy.analysis.Buffer('fire_stations', 'fire_buffer', "1000 meters")

    The distance is a numeric value but requires a linear unit as well. The value is therefore a string consisting of a number, followed by a space, followed by the linear unit. While Python is case-sensitive for the most part, the case of the unit does not matter here. Therefore, you can use "1000 meters" or "1000 METERS" or "1000 Meters"—all are considered correct. As before, you can use either a pair of single or double quotes—both are correct.

    This completes the required parameters. The tool is ready to run. You could continue to enter values for optional parameters, but that is not required for the tool to run.

  13. At the end of the line of code, press Enter to run the tool.

    The tool runs, the result is printed in the transcript of the Python window, and the resulting feature class is added to the current map.

    Output fire station buffers

    Buffer 1,000 meters result in Python window.

    In the transcript, below the line of code that ran the tool, is the result from running the tool. In this case, the result of the Buffer tool is a new feature class. Recall that in the example of the Add XY Coordinates tool, the result was a reference to an existing feature layer, not a new feature class.

    The printed result shows the location of the newly created feature class:

    <Result 'C:\\Lessons\\PythonGP\\Toronto.gdb\\fire_buffer'>

    When specifying the output feature class, only the name of the feature class was provided. Why does the feature class end up in the file geodatabase Toronto.gdb? Because that is the current workspace for the project. Code in the Python window honors the environment settings of the application.

    Note:
    Two backward slashes (\\) are used in the path instead of a single backslash (\). A single backslash in Python is used as an escape character and can have unintended consequences. Instead of two backward slashes, you can also use the letter r for raw before the string (that is, r"C:\Lessons\PythonGP\Toronto.gdb") or use a single forward slash (that is, "C:/Lessons/PythonGP/Toronto.gdb"). All three notations are considered correct and can be used interchangeably.

    You ran the Buffer tool using only the three required parameters. Next, you will run it again with one of the optional parameters.

  14. Look again at the syntax for the Buffer tool:

    arcpy.analysis.Buffer(in_features, out_feature_class, buffer_distance_or_field, {line_side}, {line_end_type}, {dissolve_option}, {dissolve_field}, {method})

    The parameter named dissolve_option specifies how overlapping buffer polygons are dealt with. The default value for this parameter is NONE, which means that all individual buffers are maintained, regardless of any overlap. You will set this value to ALL, which means that all output features will be dissolved, removing any overlap.

    Instead of retyping the earlier code, you will use a shortcut to retrieve the previous line of code.

  15. With your pointer in the prompt, press the Up arrow on your keyboard.

    This retrieves the previous line of code used to run the Buffer tool. This works for any previous lines of code. You can scroll through multiple lines of code using the Up and Down arrows. Once you have found the line of code of interest, you can make changes in the prompt and press Enter to run the code again.

  16. Place your pointer at the end of the third parameter, between the last quote and the closing parenthesis.
  17. Type a comma followed by a space.

    Line side optional parameter help

    This shows the code autocompletion prompts for the line_side parameter. The default value for this parameter is Full and there is no need to change it. Instead of specifying this value, you can skip the parameter. You can skip the parameter by specifying an empty string.

  18. Type a double quote.

    A second quote is added automatically. The code is now as follows:

    arcpy.analysis.Buffer('fire_stations', 'fire_buffer', "1000 meters", "")

    The value of the line_side parameter is set to "", which is an empty string. This means that the default value for this parameter will be used.

    The next parameter is line_end_type, which can also be skipped.

  19. Place your pointer at the end of the fourth parameter, between the last quote and the closing parenthesis.
  20. Type a comma, followed by a space, followed by a double quote.

    A second quote is added automatically. The code is now as follows:

    arcpy.analysis.Buffer('fire_stations', 'fire_buffer', "1000 meters", "", "")

    Now you can specify the value for the dissolve_option parameter.

  21. Type a comma, followed by a space, followed by a quote.
  22. From the list of options that appears, select Dissolve all output features into a single feature.

    Dissolve all output.

    This populates the parameter with the value ALL as a string. Notice how the autocompletion prompts provide a longer description, but the code shows 'ALL'. This is because the parameter keyword is ALL, and this is what you will find in the tool documentation. The longer description is the keyword label and matches the choices you see for this parameter on the tool dialog box. When typing out the code manually, you would need to type out the parameter keyword as a Python string, for example, 'ALL' or "ALL".

    The code is now as follows:

    arcpy.analysis.Buffer('fire_stations', 'fire_buffer_diss', "1000 meters", "", "", 'ALL')

    Finally, it is helpful in this case to change the name of the output feature class so it can be distinguished from the previous version that was not dissolved.

  23. Change the name of the output feature class from 'fire_buffer' to 'fire_buffer_diss'.

    Buffer with dissolve option ready to run

    arcpy.analysis.Buffer('fire_stations', 'fire_buffer_diss', "1000 meters", "", "", 'ALL')

    The tool is now ready to run.

  24. Press Enter to run the tool.

    Result in the Python window

    The resulting feature class is added to the active map and the name and path of the output feature class are printed below the line of code. The buffers have been dissolved and all overlaps removed.

    You may have wondered why it is necessary to skip the optional parameters. The reason is that in the syntax for the tool, the parameters have a predefined order. The dissolve_option parameter is the sixth parameter in that order. When parameters are not explicitly referred to by their names, this order needs to be preserved. You will see what happens when this order is not preserved.

  25. With your pointer in the prompt, press the Up arrow on your keyboard to retrieve the previous line of code.
  26. Modify the line of code by removing the two skipped parameters. The code should be as follows:

    arcpy.analysis.Buffer('fire_stations', 'fire_buffer_diss', "1000 meters", 'ALL')

  27. Press Enter to run the code.

    This results in an error:

    Value is not a member of Full error message.

    This means that ALL is used as the value for the fourth parameter, which is line_side. The only valid value for this parameter is Full, so using ALL here results in an error.

    There are several alternatives to using an empty string ("") to skip optional parameters. You can also use the number sign ("#") or the value None. As a result, the following lines are all correct and can be used interchangeably:

    arcpy.analysis.Buffer('fire_stations', 'fire_buffer_diss', "1000 meters", "", "", 'ALL')

    arcpy.analysis.Buffer('fire_stations', 'fire_buffer_diss', "1000 meters", "#", "#", 'ALL')

    arcpy.analysis.Buffer('fire_stations', 'fire_buffer_diss', "1000 meters", None, None, 'ALL')

    The number sign must be in quotes, that is, "#" not #. The number sign without quotes is used for comments in Python, so it cannot be used here.

    On the other hand, the value of None is used without quotes. None is a keyword and is its own datatype in Python. While this is not the same as an empty string, it has the same effect here. This can lead to some confusion since some tool parameters have "NONE" as one of their possible values. The value of None is used to skip an optional parameter and effectively means that the default value is used. The value of "NONE" is used to set the value of the parameter to that specific value using a string.

You've seen how to use autocompletion to get the correct syntax to run geoprocessing tools in the Python window. Now you'll see how to specify multiple parameters by name and add multiple lines of input to the Python window.

Specify tool parameters by name

Instead of skipping optional parameters that can be left to their default using an empty string, a number sign, or None, you can specify parameters by their name.

  1. With your pointer in the prompt, press the Up arrow on your keyboard.
  2. Modify the line of code to be as follows:

    arcpy.analysis.Buffer('fire_stations', 'fire_buffer_diss', "1000 meters", dissolve_option='ALL')

    Name the dissolve_option parameter.

    The dissolve_option parameter is set to 'ALL'.

  3. Press Enter to run the code.

    The tool runs correctly without error.

    You have seen several solutions to work with optional parameters that need a value other than their default:

    • Skipping optional parameters that can be left to their default by using an empty string (""), a number sign ("#"), or the None keyword, until you get to the optional parameter of interest.
    • Referring to the optional parameter of interest by its name, leaving out all other optional parameters that can be left to their default.

    All these solutions are correct, and which option you use is a matter of preference. You can stick to one particular style, but it is good to be aware of other styles, because you will see all of them in code written by others.

    Referring to tool parameters by their name can be used for optional parameters, but the same approach can be applied to all parameters—for example:

    arcpy.analysis.Buffer(in_features='fire_stations', out_feature_class='fire_buffer_diss', buffer_distance_or_field="1000 meters", dissolve_option='ALL')

    By convention, when referring to tool parameters by their name, no spaces are used around the = operator, although the use of spaces has no impact on the running of the code. Also, be aware that once you name a parameter, you must name all of the parameters that follow it.

    Notice how all these names refer to the parameter names exactly as they are written in the syntax help of the tool, which is required for this to work.

    While this makes the code considerably longer, it makes it easier to review and understand the code since the parameters are explained in the code itself. For relatively simple tools with few parameters, these explanations may not be necessary. But especially when you are reviewing existing code for more complex tools with many parameters, these explanations make it easier to understand the code without having to look up the syntax.

    One downside of using the parameter names is that the line of code may be very long—longer than the recommended maximum length of Python code of 79 characters. The solution is to break up the line of code into multiple lines.

    arcpy.analysis.Buffer(in_features='fire_stations',
                          out_feature_class='fire_buffer_diss',
                          buffer_distance_or_field="1000 meters",
                          dissolve_option='ALL')

    This breaks up the line of code into multiple lines for legibility, but it still runs as one line of code. This style uses what is called implied line continuation. Python requires that the opening parenthesis be followed by a closing parenthesis. Since this closing parenthesis does not occur in the first line, the next few lines are considered part of the same line of code until the closing parenthesis occurs. The extra white space is used for alignment purposes and is not considered indentation.

    Next, you will create these multiple lines in the Python window.

  4. Add the following code to the Python window (but do not press Enter).

    arcpy.analysis.Buffer(in_features='fire_stations', out_feature_class='fire_buffer_diss', buffer_distance_or_field="1000 meters", dissolve_option='ALL')

    Long line of code all in one line

    The next step is to break up the code into multiple lines. Normally, you do this by pressing Enter. However, in the Python window, this results in running the line of code. To add a line without running the code, you need to press Shift+Enter instead.

  5. Place your pointer after the comma following the first parameter, in_features='fire_stations', and press Shift+Enter.
  6. Add spaces before the name of the second parameter so it aligns with the first one.

    Long line of code with first line and spacing added

  7. Place your pointer after the comma following the second parameter and press Shift+Enter.
  8. Place your pointer after the comma following the third parameter and press Shift+Enter.

    Each parameter now appears on a new line, but because they are all within the parentheses, Python considers the block to be a single line of code.

    All parameters on different lines

    Aligning the tool parameters improves legibility.

  9. Press Enter twice to run the tool.

    Different Python editors handle implied line continuation slightly differently. For example, when writing a script in editors such as IDLE and PyCharm, there is no need to manually enter the first set of spaces; the alignment of multiple lines is automated.

    Breaking the parameters into multiple lines like this may seem like extra work for a gain of legibility. In the Python window, this legibility gain may not be great, but when you write longer scripts in script editor, the improvement in legibility can be significant. It is also helpful to know about implied line continuation because you will see samples that use it.

Set a workspace

The examples so far have used the Toronto.gdb geodatabase as the workspace. A workspace provides a default location for any datasets you will be working with in your code, including the input and output datasets of geoprocessing tools. When using the Python window, the workspace is controlled by the environment settings of ArcGIS Pro. You can confirm the current workspace in the Python window.

  1. Type the following code in the prompt and press Enter:

    print(arcpy.env.workspace)

    This returns the following path:

    C:\\Lessons\\PythonGP\\Toronto.gdb

    Print the current environment.

    To change the workspace, you have several options. First, you can change the workspace for your ArcGIS Pro project. This is convenient when using the Python window but does not work when using the same Python code in a Python editor outside of ArcGIS Pro, such as IDLE or PyCharm. Second, you can use the complete paths for any input and output as the tool parameter. While this works, it results in very repetitive and potentially long paths in your code. This makes your code less readable and less robust. Third, you can set the workspace using Python code, which is best practice.

    You will add a line of code to set the workspace.

  2. Type the following code in the prompt:

    arcpy.env.workspace =

    Next, you need to provide the workspace as a Python string. You can type this out, but you can also drag in the path from the Catalog pane.

  3. Click the Results.gdb in the Catalog pane and drag it into the Python prompt.

    Drag Results geodatabase to prompt to get its path.

    The path is added to the prompt.

    The path is added to the prompt.

    In addition to workspaces, you can also drag in feature classes and other data elements into your code in the Python window. Being able to drag these elements is convenient since the result is a complete path with proper formatting. This saves time and prevents typos.

  4. Press Enter to run the line of code.

    This sets the workspace and overrides the workspace at the level of the application. This means that any code run in the Python window from this point on will employ this workspace. It does not change the workspace set under Environments, so any tools run from their tool dialog box will still use the previous workspace.

    Next, you will run the Buffer tool again to see the effect of changing the workspace.

  5. With your pointer in the prompt, press the Up arrow on your keyboard to retrieve the last run of the Buffer tool.

    Set the workspace and run Buffer again.

  6. With your pointer at the end of the line of code, press Enter twice.
  7. Expand Results.gdb.

    The new feature class is added to this geodatabase.

    New feature class in the Results geodatabase.

    Note that the input feature class is fire_stations. This feature class does not reside in the current workspace (Results.gdb). However, fire_stations is a feature layer in the current map. When running geoprocessing tools in the Python window, you can use both feature layers in the current map as well as feature classes on disk as inputs. This means it is critical you understand the workspace being used.

  8. Type the following code in the prompt and press Enter:

    arcpy.management.AddXY("fountains")

    This results in an error:

    ERROR 000732: Input Features: Dataset fountains does not exist or is not supported
    Failed to execute (AddXY).

    The feature class fountains reside in the Toronto geodatabase, which is no longer the workspace for the Python window. The feature class has not been added to the active map, so it cannot be found.

    To work with a feature class that is not in the workspace, you need to first add it to the active map or use the full path. You will add the full path.

  9. Press the Up arrow to retrieve the previous line of code.
  10. Delete the feature class name, "fountains".

    The code should now be as follows:

    arcpy.management.AddXY()

  11. In the Catalog pane, expand Toronto.gdb and drag the fountains feature class into the Python prompt.

    Drag fountains feature class onto tool.

    The full path to the fountains feature class is added to the tool parameters.

    Path is added to tool.

  12. With your pointer at the end of the line of code, press Enter.

    The Add XY Coordinates tool runs without an error. Using the full path overrides the workspace just for this one line of code.

    In most scripts, you start with setting the workspace at the top of your script. There is one additional setting that is commonly employed. One of the options for an ArcGIS Pro project is to allow geoprocessing to overwrite existing datasets. This makes it easier to run the same tools multiple times. In Python, you can set this property by running this line of code:

    arcpy.env.overwriteOutput = True

    A typical script using geoprocessing tools often begins like this:

    import arcpy
    arcpy.env.workspace = <path to workspace as a string>
    arcpy.env.overwriteOutput = True

    The <path to workspace as a string> would be replaced by the actual path to the workspace.

    When using the Python window, imports and environments are controlled by ArcGIS Pro, which means these lines are not required. However, stand-alone scripts in a Python editor such as IDLE and PyCharm require the use of imports and setting environments, so it is good practice to include them.

Exporting code from the History

Finally, there is one more approach to get assistance with writing code to run geoprocessing tools. You can run a tool from its tool dialog box and export the code for that run from the History pane to the Python window.

  1. In the Catalog pane, browse to the Toronto.gdb geodatabase.
  2. Add the greenspace and etobicoke feature classes to the active map.
  3. On the ribbon, click Analysis and in the Geoprocessing group, click Tools.

    Click Analysis and click Tools.

  4. In the Geoprocessing pane, type Clip in the search bar and press Enter.
  5. Double-click the Clip tool.

    Search for and run the Clip tool.

  6. For the Input Features, select greenspace.
  7. For the Clip Features, select etobicoke.
  8. For the Output Features or Dataset, browse to Results.gdb and name the output feature class greenspace_clip.

    Clip tool ready to run.

  9. Click Run.

    The Clip tool runs and the result feature class is added to the map.

  10. On the ribbon, in the Geoprocessing group, click History.

    Open History

    The Geoprocessing History pane appears.

    You can also click Open History, at the bottom of the Clip tool window, to open the History.

  11. In the Geoprocessing History list, right-click Clip and click Send To Python window.

    The Python code to run the Clip tool is sent to the Python window. This code is referred to as a code snippet, that is, a short bit of code.

    Clip Python code sent to Python window from Geoprocessing History.

    Note:
    The other options are Copy Python command and Save as Python script. The resulting code is the same, but these options are useful when you work with a Python editor outside of ArcGIS Pro or with a Notebook.

    The first and second parameters are the names of feature data layers and do not include a path. The third parameter is the name of the output features and does include a full path. Since a workspace was previously set using arcpy.env.workspace, this path is not necessary. The final parameter (cluster tolerance, which does not show on the tool dialog box) is left to its default value None and can therefore be left out. The code can therefore be shortened.

  12. Simplify the code to be:

    arcpy.analysis.Clip("greenspace", "etobicoke", "greenspace_clip")

    Simplified version of the code from the History

  13. Run the code to verify that it works.

    Since the Clip tool was previously run with the same settings, it may appear nothing has happened. You can test this by removing the greenspace_clip layer from the active map and running the tool again. This time you will notice the resulting feature class has been added to the map.

    Now you've seen how to copy Python code from the geoprocessing history after running the tool from the tool dialog box. This is useful to learn the syntax of tools, but the code may require some cleanup to follow best practices, such as leaving out parameters that can be left to their defaults.

Review

  • Python code can be used to run geoprocessing tools. A good understanding of a geoprocessing tool will make it easier to write this code.
  • The Python window provides several features to assist with writing code, including various code autocompletion prompts and other syntax assistance.
  • Tool parameters consist of required and optional ones. Optional parameters left to their defaults can be left out of the code. When an optional parameter needs to be used, there are several options to skip the other optional parameters if necessary.
  • The results from running a tool from its dialog box can be exported to Python code as a starting point for running the tool using Python.

In this tutorial, you have learned how to run geoprocessing tools in the Python window, and how to get Python syntax help. You have learned about tool parameters, about required and optional parameters, and how to specify parameters. You have learned about how paths to data and geoprocessing environments behave in the Python window. Finally, you have learned how to copy the code for a geoprocessing tool that has been run from the Geoprocessing History to the Python window.

You may also be interested in Python Scripting for ArcGIS Pro and Advanced Python Scripting for ArcGIS Pro by Dr. Paul A. Zandbergen, published by Esri Press.