Python in VSCode: Running and Debugging

This article shows you how to use Python in VSCode. You learn how to run and debug your Python programs, and how to leverage the command-line inside VSCode to your advantage. If you followed the tutorial, you’ve read a lot about IDEs and VSCode already. If not, you might want to start with these pages:

Create or open a Python project in VSCode

A VSCode window always shows one workspace. A workspace can, in turn, show multiple folders (or: projects) if you want it to. You can have multiple workspaces open, each in its own window. However, you’ll typically work on one project at a time. When doing so, one window with one workspace will suffice.

Creating a project is simple; it’s a directory that you open with VSCode. If you are on a terminal, and it doesn’t matter if this is on Linux, MacOS, or Windows, you can create a new project and open it with VSCode as follows:

$ mkdir myproject
$ cd myproject
$ code .

The code command is a handy shortcut to open a VSCode window. If you prefer, you can also open the folder from the menu: File -> Open Folder.

The first time you open a project with VSCode, the IDE creates a new file, .vscode/settings.json, with settings that are project-specific. If you use a version control system, you may want to add the .vscode directory to the ignore list, since your coworkers probably have their own settings and preference, or even use a completely different IDE.

Run Python in VSCode

The following step-by-step guide helps you to set up VSCode correctly for running Python code.

Step 1: Select python interpreter

A system can have multiple Python interpreters. It’s important to use the right interpreter for your project since VSCode uses it not only to run and debug your code but also to provide things like auto-completion. VSCode usually does its best to detect the available Python interpreters automatically. In fact, VSCode even detects a virtualenv in your project folder. That virtualenv also contains a Python interpreter, for example, which VSCode can use. In addition, it also supports enhanced virtual environment managers such as Pipenv.

Command palette

To set the interpreter, we’ll use a feature called the command palette. The command palette gives you quick access to all functionality VSCode has to offer. It allows you to do almost everything with just your keyboard. It’s awesome and a real timesaver, so I suggest you get used to it early on.

The shortcut ‘Control + shift + P’ (Windows/Linux) or cmd + shift + P (MacOS) allows you to quickly open the command pallet. If there’s one shortcut you need to learn, it’s this one! Alternatively, you can use the menu: “View -> Command Pallet…

With the command palette open, start typing ‘Python: select interpreter’. You’ll quickly see that the auto-complete helps you out; you don’t have to type the entire text:

Open VSCode command palerte
Use the command pallet to quickly find what you are looking for

Preferably, you choose the interpreter from your virtual environment if you are using one. If not, pick an appropriate version. If you don’t know which one to pick, choose Python 3 with the latest version.

If you don’t have any choice, make sure you have Python installed on your system and opt to manually enter the path to your interpreter. You shouldn’t have to; VSCode should be able to detect a correctly installed Python interpreter.

VSCode command palette select interpreter
Pick the Python version that is appropriate for your project

Step 2: Create new Python project in VSCode

When you open VSCode for the first time, you’ll start with an empty workspace. Let’s open a folder in which we can start experimenting first. I created one beforehand, but you can use the ‘Open Folder’ dialog to create one in place too. How this works exactly differs per OS. In Windows, you can click ‘New folder’, for example:

Open folder in workspace

Step 3: Create and run a Python file in VSCode

With the interpreter configured, we can now run a Python program. Let’s create a simple program, for testing purposes. Create a new file by clicking the ‘new file’ button in the explorer at the left, or using the File menu. Call it anything you like, I called mine vscode_playground.py. If you haven’t already done so, VSCode might ask you to pick a Python interpreter at this point. Go ahead and pick one.

Copy and paste the following program into your newly created file:

import sys

if len(sys.argv) == 1:
    name = sys.argv[1]
else:
    name = 'stranger'

print(f'Hi there, {name}')

This code will see if the script received an argument. If so, it assigns that to the name variable. If not, it will call you a stranger. I deliberately made a mistake that we will try to debug later on.

To run this file, you can either use the menu Run -> Run Without Debugging or press Control + F5 (Windows and Linux) or cmd + F5 (MacOS). What happens next, is VSCode opening an integrated terminal window in which the file is run. Since we made a deliberate mistake, you should get an error similar to:

Traceback (most recent call last):
  File "vscode_playground.py", line 4, in <module>
    name = sys.argv[1]
IndexError: list index out of range

Debug Pyhon in VSCode

Debugging is one of those features that makes an IDE more powerful than a simple editor. It’s not hard to do, and can save you many hours of frantically adding print statements to your code. So let us spend a little effort on learning the basics right now!

Debug current file

Instead of using the ‘Run Without Debugging’ option, we’ll now go for the ‘Run -> Start Debugging‘ option. Alternatively, you can simply press F5. VSCode will ask you what you want to do. Since we want to run the current file, pick ‘Python File’.

The program will again crash with an error. But instead of stopping, the debugger comes in and highlights the line in which the error occurred. Since it’s complaining about the list index being out of range, let’s inspect the sys.argv list more closely!

When hovering over the text sys.argv, you get a popover that allows you to inspect the variable in detail. When hovering over sys, you will see lots of internals from the sys module. When hovering over argv, you’ll see the contents of argv:

Inspect the content of argv

Even though we didn’t supply an argument, argv still contains one element: the complete path to the current script. Something we didn’t anticipate! All we need to do now is change the comparison to: if len(sys.argv) == 2. Restart the program by pressing on the restart button at the top right, or by pressing Control + Shift + F5 or cmd + shift + F5. It should now output ‘Hi there, stranger’ and exit normally.

Create run configurations

You’ve learned a quick method to start debugging by running the current file. If you want more options, however, you can create one or more run configurations.

Click Run -> Add Configuration and VSCode will create a launch.json file in the .vscode folder. This file is prefilled with an example configuration. Modify the JSON to look like this:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Run with argument",
            "type": "python",
            "request": "launch",
            "program": "vscode_playground.py",
            "console": "integratedTerminal",
            "args": ["Erik"]
        }
    ]
}

This configuration supplies an argument to the script: the name ‘Erik’. Note that it also specifically starts vscode_playground.py instead of the current file. You can now launch the debugger using this configuration. But first, let’s open the Run/Debug view in the panel on the left, by clicking on the large run button with the little bug on it, or clicking Ctrl+Shift+D or Cmd+Shift+D:

Open the run and debug view by clicking the button or pressing Ctrl+Shift+D

At the top of this view, you should see your newly created configuration. Start it by clicking on the play button next to it. The output should now say ‘Hi there, Erik’.

Breakpoints

At some point, you want to use so-called breakpoints: a line in your program at which you want to explicitly pause the execution, or take a break, so you get a chance to inspect the state of your program at that point. Adding a breakpoint is extremely easy. In the so-called gutter, the space at the left of a file where the line numbers are displayed, you can click right before a line number. A vague red dot should appear when you hover there, and it will turn bright red once you click it:

A breakpoint, where execution will pause

If you run the program now, it will pause on the breakpoint, allowing you to inspect the variables at that point in time. To continue, you can click the continue button or press F5. The debugger will continue execution until it encounters another breakpoint or the program finishes.

Alternatively, you can execute the program step by step from here on, by using the step over (F10), step into (F11), and step out (F12) buttons. This way, you can execute the program line by line, and optionally step into and out of function calls.

You now have a solid base level of knowledge to start debugging in VSCode. For more details, I’d like to refer you to the excellent debugging section of the VSCode documentation, which should be an excellent continuation of what I’ve taught you so far.

Run selection or current line

Another helpful feature is the ability to run a selection of code or the current line you’re on. This won’t always be useful: often, a line of code or selection of code heavily depends on its context. But sometimes, it can come in handy. To run a selection of code or the current line, press Shift+Enter or use the command palette and search for ‘run selection in terminal’.

The code runs in a Python REPL, and once finished, this REPL stays open so you can experiment, inspect variables, etc. For example, if you ‘run’ a function, you can now call that function from the REPL since it is defined there.

A cool feature is that all subsequent commands to run a selection or current line are executed in this same REPL, keeping the state intact. So if you change the function and ‘run’ it again, the function gets redefined in the REPL. It’s a nice hack to test the code you just wrote, but it’s not a replacement for proper unit testing.

Running code from the terminal

VSCode has an integrated terminal, which can be extremely useful. Some people never use it, and others use it all the time. I’m part of that last group: I run my code from the command line unless I’m debugging. I also do version control on the command line. I find it very useful to be familiar with all the command-line tools. It allows me to perform the crucial tasks without an IDE, e.g., on someone else’s PC, a remote terminal, or just a quickly opened up terminal window instead of opening a complete IDE.

Besides my personal preference, there are several use cases in which it’s easier to use the terminal instead of the GUI. For example: when you are testing with command-line options. You can add options in a run profile, but it’s quicker to use the terminal if those options constantly change.

So let’s explore how to run your code from the integrated terminal window as well.

Step 1: open the built-in terminal

Use the Command Palette to run Terminal: Create New Integrated Terminal, or use the shortcut Ctrl+Shift+` (that’s a backtick). A terminal should open at the bottom of your screen. By pressing that key combination again, you can create more terminal windows. You can show and hide the terminal panel quickly by pressing Ctrl+` repeatedly.

Step 2: run your code

Don’t forget to activate your virtual environment if you have one. Next, run your Python file as you would with any other file:

$ python3 vscode_playground.py Erik
Hi there, Erik

VSCode and Python Virtualenv

When using a Python virtual environment, you need to let VSCode know. As mentioned earlier, the way to do this is to select the interpreter from your virtual environment instead of the system-wide one.

To test this, let’s create a virtual environment first:

python3 -m venv venv

As you can see from the screenshot, VSCode almost instantly noticed that we created this venv and offers to use it:

Click yes, and you’re done! Alternatively, you can manually select this venv in the command palette (Ctrl+Shift+P) by typing ‘select interpreter’ and clicking on ‘Python: select interpreter.’

Formatting Python in VSCode

You can format Python in VSCode if you hit Ctrl+Shift+I (that’s an uppercase i). VSCode by default formats the current document. If you haven’t done so, it asks you if you want to install a formatter like autopep8, black, or yapf. Pick one (the default, if you are unsure), and let it install.

From now on, if you press Ctrl+Shift+I while editing a Python file, you’ll notice that your file gets formatted according to the default rules of the formatter. If you want to customize these rules, you will need to look up (e.g. on Google) how to do that for the specific formatter you picked. Usually, you can add or modify rules by creating a specific file in your project’s main directory.

Saving a workspace

Finally, you might want to save your workspace. It’s not necessary, though. You can simply open the folder again. Customizations like your launch configurations are kept in the (hidden) .code directory, and VSCode will find this if you open the folder. However, if you opened multiple folders in your workspace and don’t want to repeat those steps continually, you can save the workspace using the File -> Save Workspace As.. menu.

Keep learning

Read these articles to learn more about Visual Studio Code and its features:

The following external link might be helpful too:

About the author

Erik is the owner of Python Land and the author of many of the articles and tutorials on this website. He's been working as a professional software developer for 25 years, and he holds a Master of Science degree in computer science. His favorite language of choice: Python!

Leave a Comment