Using VS Code

ENV 859 - Geospatial Data Analytics   |   Fall 2024   |   Instructor: John Fay  

Introduction

Python scripts are simply text files with a .py extension; you can open them and read them - even write them - in Notepad, WordPad, Notepad++, etc. However, working with Python scripts is more easily done in an integrated development environment (IDE) as these IDEs offer tools to auto format scripts as you write them, to debug them, and even to execute Python statements or chunks of scripts interactively.

Learning Objectives

Section On completion of this lesson, you should be able to:
1. Setting up theVS Code IDE Set up VS Code to work with the ArcGIS Pro installation of Python
2. Writing Python in VS Code Familiarize yourself with VS Code’s layout
Create a coding workspace in VS Code
Create and run a Python script file in VS code
3. Debugging in VS Code Use VS Code’s code tools to identify and address syntax errors
Run code in chunks or one line at a time to identify logical errors
Use the interactive Python terminal while debugging
Run code in Debug Mode

1. Setting up the VS Code IDE

Our choice of IDE for this class will be Visual Studio Code, or VSCode. It is a free, popular, and powerful IDE that can be used with many scripting languages. It’s been installed on NSOE machines, but you are certainly welcome to download and install it on your personal/virtual machines. The installation files are here: https://code.visualstudio.com/.

Once installed, however, VS code is not yet configured for Python, let alone ArcGIS Pro’s unique installation of Python. The tasks below guide you through this process. Once complete, these settings are saved in the local machine, so if you continue working on that specific machine you won’t have to repeat these steps. However, if you move to a new NSOE machine, you will likely have to repeat these steps.

» Task 1.1: Install the Python and Jupyter Extensions

Our first task is to install the Python and Jupyter extensions for VS Code, and once installed, tweak a few settings so it works with the ArcGIS Pro installation of Python already installed on our machines.

  1. Open the VS Code application. (Complete information on the VS Code interface is here. )
  2. Open the Extensions pane, either by clicking the extensions icon (the last icon on the Activity Bar on the left side of the interface), or by pressing <Ctrl+Shift+X>.
  3. Install the Python extension, likely the top of the “Popular” list, but if not, you can search for it. Note that when you install the extension other extensions may also get installed, e.g. “Pylance”.
  4. Do the same for the Jupyter extension.

» Task 1.2: Modify the Python settings to work with the ArcGIS Pro installation of Python

Without getting into overwhelming detail, we need to tweak one setting to enable VS Code to work smoothly with ArcGIS Pro’s version of Python.

  1. Open the VS Code Settings (<Ctrl+,> ).
  2. Search for terminal.activateEnvironment.
  3. De-select the Python > Terimal: Activate Environment setting.
  4. Search for python.REPL
  5. De-select the Python.REPL:Send to Native REPL setting.
  6. De-select the Python.REPL: Enable REPLSpartSend setting.
  7. Search for jupyter.interactiveWindow.textEditor.executeSelection
  8. Select the Jupyter > Interactive Windows > Text Editor setting

♦ Task 1.3 Set the Python interpreter

Next, we need to point VS code to where on our machine Python is installed, called the “Python interpreter”.

  1. Open the Command Palette (<Ctrl+Shift+P>) and type Python: Select Interpreter
  2. Click the + Enter interpreter path..., then select Find...
  3. Enter the path: C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\python.exe

♦ Task 1.4 Test the Python installation:

Time to check that our installation is working…

  1. From the File menu, select New File
  2. Specify the new file to be a Python File
  3. Write some code in the new file, something that produces an output (e.g. “print("Hello World)”)
  4. Save the file (anywhere for now…).
  5. Run the file by clicking the right-facing triangle (►) in the upper right of the app.

    :warning:Note: Run without Debugging (ctrl-F5) used to be a viable alternative to hitting the ► button, but it now has slightly different behavior. Stick with hitting ►.

  6. Check that your code produces the correct output in the terminal. (We’ll explain this process in more depth below. For now, just look for the output somewhere in what’s printed to the screen.)

If all went well, VS Code is set up to code Python on your machine. Of course, if you move to a machine you’ve not logged into before (or someone has wiped your profile), you’ll need to repeat these steps to re-configure VS Code.

Optional: Set up VSCode to Synchronize settings across machines

  • Open your machines default browser and sign into https://github.com. (If you don’t have a GitHub account, now is the time to create one…)
  • In VSCode, Select File > Preferences> Turn on Settings Sync....
  • In the “Setting Sync” dialog box that appears, click the “Sign in & Turn on” button.
  • You’ll be asked which account to use: GitHub or Microsoft. Select “Sign in with GitHub.
  • Follow the instructions to authenticate VS Code using GitHub. Typically, a browser window should appear asking you to Open Visual Studio Code, where you should click the button to do so.

Now if you go to a new machine and open VS Code, you can turn the “Settings Sync” to on and your local VS Code app will pull your saved settings from your GitHub account, updating your local configuration!


2. Writing Python in VS Code

You may have just gotten comfortable writing and running Python code in Jupyter Notebooks. As well see soon enough, writing Python scripts in an IDE (vs Notebooks in Jupyter) has distinct advantages, but we still have to get a bit used to a new set of procedures for just writing, running – and debugging – code in script formats. We’ll begin by looking at the basic procedures for writing code in VS Code, looking a few of the nifty tools that VS Code offers.

♦Task 2.1 Create a VS Code workspace

VS Code, like ArcGIS Pro, is project based, meaning it prefers to organize files within project folders. So, we’ll start by creating a workspace folder and opening that folder in VS Code.

  1. Create a project folder to hold some Python scripts.
  2. In VS Code, select File>Open Folder...
  3. If a window appears asking you to trust this folder, go ahead and trust it.

The folder should open up in the Side Bar. At present, there are no files in the folder, so we’ll add one.

♦ Task 2.2 Create a new Python script in your workspace folder and run it

Now let’s create a Python script and run it…

  1. Create a new file (File>New File>Python File.)

  2. Save the file as “Test.py” in the folder you created in the previous step.

  3. Type (or copy and paste) the following code:

    # My test code
    myData = ["Cat","Dog","Mouse"]
    print(myData[1])
    

    Note how VS Code colors the text through a process called “linting”. Can you tell what the significance of the colors are? How does this help you code? (Also, you can change the color scheme by selecting a different theme via the gear (:gear:) icon in the lower left.)

  4. Hover the mouse over various elements in your code and note what information is revealed.

  5. Save the file.

  6. Run the file by clicking the right-facing triangle (►) in the upper right of the app.

    When run, a Terminal opens and reports your output and/or any errors that occurred when you ran your scripts. Read more about VS Code terminals here.

    Did your code run successfully?


3. Debugging in VS Code

Debugging code requires finding where the bug occurs and modifying the code to fix the error. The three most common types of coding errors are syntax errors, runtime errors and logic errors. They are explained below:

  • Syntax errors occur when Python doesn’t understand your command. These are common and usually easy to identify and fix as the IDE will often flag exactly where the error occurs. These can be typos in a function name (e.g. pritn instead of print), forgetting a closing parenthesis, or violating Python’s code structure (e.g. forgetting a : or messing up the indentation).

  • Runtime errors occur when Python understands each of your commands, but the applications of your commands violates some rule. An example would be when you try to add a variable holding a string value to another variable holding a numeric value: Python doesn’t understand how to add a number to string.

    These errors can be more challenging to find and fix as they are only raised when you run the script. Sometimes the error messages are useful and indicated exactly where the error can be fixed, but not always. Often debugging runtime errors requires running your code bit by bit, investigating the value of variables at certain places in your script and seeing precisely which line trips the error.

  • Logic errors are the hardest to identify and fix. Here you code runs fine to completion, but its product is not correct. For example, you need to extract the first value from a list, but you forgot that Python list indices start at zero and you provide the index of 1 and get the second item. Python does what you programmed it to, but it’s not correct.

    Debugging logic errors can be quite tricky. You need to constantly inspect your values just to identify that you have a logic error. And then, you need to meticulously check variable values at various points in your code to ensure the values are what you expect.

Given these types of errors, IDEs likeVS Code provide useful tools for debugging code. Let’s have a look at a few.

♦ Task 3.1 Addressing syntax errors

VSCode is good at revealing syntax errors. Sometimes it’s obvious what to do; sometimes not.

  • Replace the contents of the script above with the following (which has lots of errors, both syntax and runtime) and save the script:

    ENV 859: Exercise 5 
    name = "Amelia"
    pronoun = "She"
    age = 4
    class = "Panda bears"
    print (name + " is " + age + " years old.")
    print (pronoun + " is in the " + class + " class.")
    

    Note that VS code reveals possible errors in your code shown by the red underlines.

  • Navigate to the terminal (Use the Terminal>New Terminal if you closed it), and select the Problems tab. This reveals the errorsVS Code found and where they occur. You can also hover over the errors to investigate what the error is.

    • Fix the error(s) on the first line, which should be a comment.

    • Another error appears on line 5. Note that the word “class” is blue. *This indicates that the word is a reserved word that cannot be used as a variable name.*

      Rename all instances of the variable name “class” to “class_name”.

  • VS Code can’t find any more errors! Try running the script…

    You’ll get another error showing up in your console. In this case, the error message states where the error occurs. Some error messages are not as kind and don’t reveal exactly where the error occurs. For this we need debugging tools.

♦ Task 3.2 Addressing runtime errors by running lines selectively

To identify where our runtime error is we can run lines selectively. We can run one or several lines by selecting them in our code and hitting shift-enter. This enables us the ability to zero in on where our error might occur. It also opens the interactive Python prompt (“”) in the terminal window allowing us to type Python commands.

Running selected lines of code in the terminal
  • Highlight the first 5 lines and hit shift-enter. The lines are run as shown in the terminal window.

    :mega: Note: It’s possible that shift-enter opens an “Interactive Window”, which is fine! If so, skip to the next section.

  • Highlight line 6 - or just put the cursor anywhere on the line - and run it. The error appears, indicating this is where it occurs.

  • At the Python interactive prompt, type age = "4".

  • Re-run line 6. No error! We’ve identified the error and the solution. We could now amend our actual code in the script to fix the error, but don’t do that yet.

  • Close your terminal.

Running selected lines of code in an interactive window
  • Highlight the first 5 lines as you did above, but this time right-click on them and select “Run in Interactive Window>Run Selection/Line in Interactive Window”.

    → A new pane will appear. This is the interactive window and allows you to explore your code more, well, interactively.

  • Click on the Variables tab in the interactive window. You can now see the values of the different variables declared so far in your code.

  • Run link 6 in the interactive window.

  • At the bottom of the interactive window is a Python prompt which works the same as the interactive Python prompt in the terminal.

Both these methods allow you more control of how you run your code than Jupyter notebooks, giving you more precision for identifying and addressing coding errors.

♦ Task 3.3 Addressing errors by running code in debug mode

Here we’ll look atVS Code’s debug mode. This allows even more control in running code line by line. Debug tools can also be useful when debugging long scripts as it allows us to, instead of selecting chunks of code to run, we can use breakpoints to run code up to a set point.

Using the debugger
  • Run your code in Debug Mode by hitting F5. This runs your code until an error is raised, indicating where it has been raised.

    :mega:You may get asked to “Select a debugger”. If so, select “Python Debugger”.

  • We can still type Python commands, but now in the debug console, not the terminal.

  • Exit the debugger by hitting the red square at the top of the script, in the debug controls toolbar, or hitting shift-F5.

Using breakpoints
  • Click just to the left of line 4 so that a red dot appears. This is a breakpoint, telling Python to run everything up to that line.
  • Run the script in debug mode. The cursor stops at line 4 without executing it.
  • In the debugging controls at the top of the script, select “Step over” (F10) to run that line and move to the next.
  • Continue “stepping over” until the error appears.

♦ Task 3.4

Finally, we’ll look at a debug technique that leverages both debug mode and the interactive window. To do this we, divide our code into code chunks, much like code cells in Jupyter Notebooks. And then we can debug these code chunks individually in the interactive window, which gives better introspection of the variable values.

  • Replace the comment hashtag in line 1 with #%%. This converts our code into a code chunk.
  • Add a new blank line between lines 5 and 6 and then another new line. In the second new line (now line 7), type #%% to create a second code chunk.
  • Run each code chunk individually. The first should run fine and the second should raise the error.


Which debug option to use?? I suggest testing them all and seeing which one you prefer. I personally find each has its own usefulness, mostly depending on how complex my script is. If it’s short, I’ll just run lines by highlighting them; and if it’s a long bit of code, I find the debug tools quite helpful.


Recap

Integrated Development Environments, or IDEs, help us write scripts. Fundamentally, they are text editors linked to a Python kernel that can execute our Python scripts, but they also provide code formatting, code completion, a Python shell, debugging tools, and many other features that enable us to interactively write and debug our code.

We’ll gain plenty more experience and comfort with these tools as we use them to write and debug more code.