Configuring VS Code for ArcPy/ArcGIS Pro development

Recently, I have found myself using Esri’s ArcGIS Pro and its companion Python package, ArcPy, more and more often. For the unfamiliar, this is geographic information system (GIS) software, primarily used to visualize and analyze geographic data. Python is commonly used to automate these analysis tasks within the software, and ArcPy exposes programmatic access to many features of ArcGIS. However, the way Esri delivers the ArcPy is a bit atypical in my experience, especially if you’re more familiar with open source Python implementations. ArcGIS Pro ships with a built-in Python interpreter that has the ArcPy site package baked in, containing a massive collection of Python modules. The ArcGIS Pro Python interpreter also includes Conda as the package manager and can be used via the standard terminal commands, but Esri also provides a cool GUI to manage Conda environments and dependencies.

The default tools that ship with ArcGIS Pro’s Python tools are limited, but that is to be expected. IDLE is of course available, and a Python CLI is installed as well; it integrates nicely with Windows Terminal and is also available from within ArcGIS Pro

IDLE – the default IDE installed with ArcGIS & Python
ArcGIS Pro cloned Python environment in Windows Terminal
ArcGIS Pro’s Python Window

Like three quarters of developers out there, I use Visual Studio Code in some capacity, so I wanted to be able to do all the necessary ArcGIS Pro Python coding and debugging from within my preferred development environment. Unfortunately, Esri leaves a lot to be desired looking at their documentation for using ArcPy within popular IDEs and editors like VS Code… I did some digging around the interwebs, reading a lot about ArcPy and ArcGIS Pro development, and put together a local development environment and configuration over the course of several months of experimentation which works well for me. My requirements for ArcGIS/ArcPy development tooling were pretty straight forward:

  • Integration with VS Code, including:
    • Linting & IntelliSense code completion working
    • Debugging, including being able to hit breakpoints
    • ArcGIS Pro’s Python package manager can remain the default for dependencies
  • No requirement to paste boilerplate or other “hacky” code to make things work as desired (I’ll clarify this in the last section).

After some trial and error, I was able to get everything configured to my liking. The first, and perhaps the most important, step is to set the location of the ArcGIS Python interpreter. This effectively “enables” ArcPy within VS Code. That is located here: %LocalAppData%\Programs\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\ however, Esri actually recommends not using this default Python environment, and instead using a cloned environment. This will allow packages to be add/removed without risk of breaking any tools or dependencies in the default environment.

My various Python environments, cloned from the default “arcgis-py3” environemnt

I initially went down the path of setting “python.exe” from my cloned environment as the Python interpreter in VS Code which does seem to work OK. However, I observed some errors in the terminal indicating things may not actually be configured correctly. Before continuing, it may be helpful to take a look at my post on the Esri Community forums for more details; a user there, BrianWilson7, provided guidance that led to the solution I’m documenting here.

Open the VS Code settings (File > Preferences > Settings), search for “python”, and locate setting “Python: Conda Path” and paste the folder which contains the Conda environment; on my machine, the folder is located here: %LocalAppData%\Programs\ArcGIS\Pro\bin\Python\Scripts but it could also be found in one of the Program Files folders, depending on the installation. This folder contains “conda.exe”, IDLE, and other scripts/utilities.

The Conda environment folder – this may be in a different location on your machine

Before closing the settings, ensure that “Python: Default Interpreter Path” is not set to any value. After verifying this, the settings menu can be closed, and VS Code must be closed. Before starting VS Code again, the Windows PATH environment variable for the user needs to be modified. Search for and run “Edit the system environment variables” in the start menu.

Click the “Environment Variables…” button when the utility launches opens, then click the “Edit…” button for the current user and add the same Conda environment path above.

Add a new entry to the list, using the same Conda environment folder.

On VS Code restart, the Conda environments from ArcGIS Pro should now be configured and available to use. The currently selected Python environment can be changed in couple different ways: selecting it on the bottom status bar, or by opening the VS Code command palette and searching for “Python: Select Interpreter.” See the VS Code docs for more information. It is important here to note the paths set in File > Preferences > Settings above should not be changed unless your ArcGIS installation changes. These values do not need to be changed when cloning new environments.

Almost there…one more VS Code restart is required. On re-launch, again open PowerShell in the VS Code terminal. You may see errors in the terminal similar to this:

If so, close VS Code again, delete file %UserProfile%\Documents\WindowsPowerShell\profile.ps1 and then restart VS Code. PowerShell in the Terminal windows should open as excepted, without the above “CommandNotFound” error message. Next, from within the open PowerShell Terminal window, enter command proenv which will bring up the environment’s shell. Enter command activate my-cloned-environment. Run conda info to verify the environment is activated.

Now that everything is wired up, the next step is to test debugging of a Python script. While still in the Conda environment’s shell, noted by the (arcgispro-py3-clone-3.0.2) prefix in front of the directory prompt, open a working .py file, set a breakpoint, and press F5 to debug. Select the “Python File…” option.

The Python Debug console should start up, the script will begin to execute, and the breakpoint will be hit. In the screenshot below you can see the all the modules within the ArcPy package are visible, and VS Code IntelliSense works as expected when writing ArcPy code.

IntelliSense in working with ArcPy

I typically prefer to create one or more debug profiles within a project; I find it makes frequent starts & stops of the code while testing a little easier. To create a debug profile, click the Debug button on the left to open the debug panel and then click “create a launch.json file.” Alternatively, select Run > Add Configuration from the menu bar.

Select the “Python: Current File” template, and then a new “launch.json” file inside a “.vscode” folder at the root of your project. Inside, an launch configuration for Python will be automatically stubbed out.

This config file is meant to be user-editable, and there are many additional options so be sure to refer to the VS Code docs on debugging to learn more. I changed the name of my profile for demonstration purposes, as this is how each individual configuration is identified in the drop down menu on the debug controls:

This should be sufficient for standalone script development with ArcPy, but I still wanted a little bit tighter integration with ArcGIS Pro and VS Code when it comes to debugging Python toolboxes. Unfortunately, at this time, there does not appear to be the ability for VS Code to attach to and debug a running arcgispro.exe Python process as PyCham and Visual Studio do. While that is a really nice feature to have, it is possible to structure the code in a way that it can be executed in both ArcGIS Pro as tools in toolboxes, and as a standalone script for testing and debugging purposes.

At the beginning of this post I mentioned that I didn’t want to have to rely on pasting in or commenting/un-commenting boilerplate code or using some other hacky methods when switching between running the code in Pro and VS Code. To tighten this integration, I structured my Pro toolbox code in a way that allows it to be run from Pro or VS Code, unmodified. This is accomplished by breaking each tool that is part of a .pyt Python Toolbox into its own separate class, in a separate .py file. The tool.py file only defines the tool’s class – there is no code to instantiate the class or do anything else, so if the file is run, the script will just exist immediately without doing anything. This is the desired behavior when running the Python toolbox in ArcGIS Pro.

When actively developing/testing/debugging a particular tool, I need deep debugging control, not having to reply on printing information to the output message window. In order to debug my tool in VS Code, I added a hook to the .py file that will check for a specific parameter I will pass in when starting the script, “DEBUG.” The code snippet below is added to the bottom of the tool.py file:

if sys.argv[-1] == "DEBUG":
    # add your debug code here
    pass

Passing in that “DEBUG” argument is done via the debug configuration set in launch.json. An “args” property can be added, which contains an array of the arguments that should be passed in when the debugging session start. Since my tool has a one user input parameter (a name), I also include that in the args array.

{
    "configurations": [
        {
            "name": "Debug MyTool.py",
            "type": "python",
            "request": "launch",
            "program": "${fileDirname}\\MyTool.py",
            "console": "integratedTerminal",
            "args": ["DEBUG"]
        }
    ]
}

Any number of parameters can be passed in here, and you may find that having multiple debug configurations with different arguments is useful. The only requirement is that the last argument be “DEUBG” so that the condition is met, and custom debug code can be added.

I hope this helps other ArcPy developers out there. I welcome any comments, suggestions, corrections, or other feedback on this tutorial. I am not an expert Python developer, but since I wasn’t able to find a whole lot of information or comprehensive tutorials on configuring VS Code for ArcPy, I would like this post to be accurate and a valuable reference for other VS Code & ArcGIS users.

One thought on “Configuring VS Code for ArcPy/ArcGIS Pro development

  1. It would be nice if we could force proenv to run before vsc tries to activate the env when just running the script from the RUN button.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s