How to debug a Streamlit application in VS Code (Windows, PowerShell)

Streamlit is a Python framework that makes it easy to build simple data driven apps, especially chat-with-your-data style apps that take advantage of Generative AI.

Normally, you run Streamlit from the command line.

python -m streamlit run main.py

Here is how to set up your Python debugging VS Code launch profile so you can easily debug these Python Streamlit applications.

First, you need to find where your Streamlit Python package is located.

If you are using a Python virtual environment, you need to activate your virtual environment first (PowerShell). My virtual environment is called “.venv”, substitute with the name of your virtual environment.

./.venv/Scripts/activate

Otherwise, you can run the following Python directly from the command line. The difference is that a virtual environment makes its own copy of the Python executable and all associated packages.

python

import streamlit

print (streamlit)

This will output the module’s path.

<module 'streamlit' from 'C:\\Users\\dkschrute\\source\\repos\\demoapp\\src\\.venv\\Lib\\site-packages\\streamlit\\__init__.py'>

We need just the path to the streamlit package.

C:\\Users\\dkschrute\\source\\repos\\demoapp\\src\\.venv\\Lib\\site-packages\\streamlit

In VS Code, we need to create a launch.json file in the .vscode directory of your app. Add the following JSON.

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python Debugger: Current File",
            "type": "debugpy",
            "request": "launch",
            "program": "C:\\Users\\dkschrute\\source\\repos\\demoapp\\src\\.venv\\Lib\\site-packages\\streamlit",
            "console": "integratedTerminal",
            "cwd": "${workspaceFolder}/src",
            "args": [
                "run", 
                "main.py"],
            "justMyCode": false
        }
    ]
}

The most important key/value pair to change is the program key. It needs to be set to where the streamlit package is stored.

If your streamlit package is inside a virtual environment in this app (as mine is in the above example), you can simplify this path.

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python Debugger: Current File",
            ...
            "program": "${workspaceFolder}/src/.venv/Lib/site-packages/streamlit",
            ...
        }
    ]
}

Leave a Reply

Your email address will not be published. Required fields are marked *