Skip to content

How to Install and Run Streamlit in VS Code: Complete Setup Guide

Updated on

Setting up Streamlit inside VS Code should be straightforward, but developers frequently hit walls. The Python interpreter points to the wrong environment. The terminal says "streamlit: command not found" even after installation. Breakpoints refuse to trigger. Port 8501 is already in use from a previous session that never terminated. These issues turn a five-minute setup into an hour of Stack Overflow searching.

The frustration multiplies when you realize most Streamlit tutorials gloss over the editor configuration. They show streamlit run app.py and assume everything works. But in practice, VS Code needs specific interpreter settings, launch configurations, and extension support to provide a productive Streamlit development experience. Without proper setup, you lose auto-complete for Streamlit widgets, debugging becomes impossible, and import errors appear despite packages being installed.

This guide walks through every step of configuring VS Code for Streamlit development, from creating an isolated virtual environment to advanced debugging with breakpoints and variable inspection. Each section addresses the real errors developers encounter and provides tested solutions.

📚

Prerequisites

Before starting, make sure you have the following installed on your system:

RequirementMinimum VersionHow to Verify
Python3.9+python --version
pip21.0+pip --version
VS Code1.80+code --version
VS Code Python ExtensionLatestCheck Extensions panel

Install the Python extension for VS Code by searching for "Python" in the Extensions sidebar (Ctrl+Shift+X on Windows/Linux, Cmd+Shift+X on macOS) and installing the one published by Microsoft. This extension provides IntelliSense, linting, debugging support, and interpreter management that Streamlit development depends on.

Step 1: Create a Project and Virtual Environment

Never install Streamlit into your system Python. A virtual environment isolates your project dependencies and prevents version conflicts across projects. VS Code integrates tightly with virtual environments once configured correctly.

Option A: Using venv (Built-in)

Open VS Code, create a project folder, and run these commands in the integrated terminal:

mkdir streamlit-project
cd streamlit-project
python -m venv .venv

Activate the environment:

# macOS / Linux
source .venv/bin/activate
 
# Windows (PowerShell)
.venv\Scripts\Activate.ps1
 
# Windows (Command Prompt)
.venv\Scripts\activate.bat

Option B: Using uv (Faster Alternative)

The uv package manager creates virtual environments significantly faster than venv and handles dependency resolution more efficiently:

pip install uv
uv venv
source .venv/bin/activate   # macOS/Linux
# .venv\Scripts\activate    # Windows

Option C: Using Conda

If you work within the Anaconda or Miniconda ecosystem:

conda create -n streamlit-env python=3.11
conda activate streamlit-env

Tell VS Code About the Environment

After creating the environment, VS Code needs to know which Python interpreter to use. Press Ctrl+Shift+P (Cmd+Shift+P on macOS) to open the Command Palette, type "Python: Select Interpreter," and choose the interpreter inside your .venv folder. This ensures the integrated terminal, IntelliSense, and debugger all use the correct environment.

If your .venv does not appear in the list, click "Enter interpreter path" and browse to .venv/bin/python (macOS/Linux) or .venv\Scripts\python.exe (Windows).

Step 2: Install Streamlit

With your virtual environment activated, install Streamlit:

pip install streamlit

Verify the installation:

streamlit version

You should see output like Streamlit, version 1.41.x. If the command is not found, your terminal is likely not using the virtual environment. Check the bottom-left corner of VS Code to confirm the correct Python interpreter is selected.

For a reproducible setup, create a requirements.txt file:

streamlit>=1.41.0
pandas>=2.0.0

Then install from the file:

pip install -r requirements.txt

Step 3: Write Your First Streamlit App

Create a file named app.py in your project root:

import streamlit as st
import pandas as pd
 
st.set_page_config(page_title="My Streamlit App", layout="wide")
 
st.title("Streamlit in VS Code")
st.write("This app demonstrates core Streamlit widgets running inside VS Code.")
 
# Sidebar controls
st.sidebar.header("Configuration")
name = st.sidebar.text_input("Your name", value="Developer")
num_rows = st.sidebar.slider("Number of rows", min_value=5, max_value=100, value=20)
 
# Generate sample data
data = pd.DataFrame({
    "Category": [f"Item {i}" for i in range(num_rows)],
    "Value": [i * 3.14 for i in range(num_rows)],
    "Status": ["Active" if i % 2 == 0 else "Inactive" for i in range(num_rows)]
})
 
st.subheader(f"Hello, {name}! Here is your data:")
 
# Display metrics
col1, col2, col3 = st.columns(3)
col1.metric("Total Items", len(data))
col2.metric("Active", len(data[data["Status"] == "Active"]))
col3.metric("Average Value", f"{data['Value'].mean():.2f}")
 
# Display the dataframe
st.dataframe(data, use_container_width=True)
 
# Simple chart
st.line_chart(data.set_index("Category")["Value"])

This example includes a sidebar, metrics, a data table, and a chart, giving you a realistic starting point rather than a bare-bones "Hello World."

Step 4: Run Streamlit from the VS Code Terminal

Open the integrated terminal in VS Code:

  • Windows/Linux: Ctrl+Shift+` (backtick) or Ctrl+J
  • macOS: Cmd+J

Run the app:

streamlit run app.py

Streamlit starts a local server and opens your default browser at http://localhost:8501. The terminal displays output like:

  You can now view your Streamlit app in your browser.

  Local URL: http://localhost:8501
  Network URL: http://192.168.1.100:8501

Specifying a Custom Port

If port 8501 is occupied, specify a different port:

streamlit run app.py --server.port 8502

Disabling Automatic Browser Launch

To prevent the browser from opening automatically each time:

streamlit run app.py --server.headless true

You can make this permanent by creating .streamlit/config.toml in your project:

[server]
headless = true
port = 8501
 
[browser]
gatherUsageStats = false

Step 5: Configure VS Code for Streamlit Development

Proper VS Code configuration eliminates linting false positives and ensures consistent formatting across your team.

Workspace Settings

Create .vscode/settings.json in your project:

{
    "python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python",
    "python.analysis.typeCheckingMode": "basic",
    "python.analysis.autoImportCompletions": true,
    "python.analysis.diagnosticSeverityOverrides": {
        "reportMissingImports": "warning"
    },
    "files.associations": {
        "*.py": "python"
    },
    "editor.formatOnSave": true,
    "python.formatting.provider": "none",
    "[python]": {
        "editor.defaultFormatter": "ms-python.black-formatter",
        "editor.tabSize": 4
    }
}

On Windows, change the interpreter path to ${workspaceFolder}\\.venv\\Scripts\\python.exe.

Recommended Formatter and Linter Setup

Install these VS Code extensions for consistent code quality:

ExtensionPurposePublisher
Black FormatterAuto-format on saveMicrosoft
Pylint or RuffCatch errors and enforce styleMicrosoft / Astral
PylanceFast IntelliSense and type checkingMicrosoft

Ruff is a modern alternative to Pylint that runs significantly faster and combines linting with formatting in a single tool:

pip install ruff

Debugging Streamlit Apps in VS Code

Debugging is where VS Code provides the most value over running Streamlit in a plain terminal. You can set breakpoints, inspect variables, step through callback functions, and watch data transformations in real time.

Setting Up launch.json

Create .vscode/launch.json with the following configuration:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Debug Streamlit",
            "type": "debugpy",
            "request": "launch",
            "module": "streamlit",
            "args": [
                "run",
                "${file}",
                "--server.port",
                "8501",
                "--server.headless",
                "true"
            ],
            "console": "integratedTerminal",
            "justMyCode": true,
            "env": {
                "PYTHONPATH": "${workspaceFolder}"
            }
        },
        {
            "name": "Debug Streamlit (All Code)",
            "type": "debugpy",
            "request": "launch",
            "module": "streamlit",
            "args": [
                "run",
                "${file}"
            ],
            "console": "integratedTerminal",
            "justMyCode": false
        }
    ]
}

The first configuration (justMyCode: true) only stops at breakpoints in your code, skipping Streamlit's internal execution. The second configuration steps into Streamlit source code as well, useful when diagnosing unexpected widget behavior.

How to Debug

  1. Open your Streamlit script in VS Code.
  2. Click in the gutter to the left of a line number to set a breakpoint (a red dot appears).
  3. Press F5 or click "Run and Debug" in the sidebar.
  4. Select the "Debug Streamlit" configuration.
  5. Interact with your app in the browser. When execution hits a breakpoint, VS Code pauses and shows the call stack, local variables, and watch expressions.

Debugging Tips for Streamlit

Streamlit reruns the entire script on each interaction, which means breakpoints trigger on every widget change. To debug only specific conditions:

import streamlit as st
 
value = st.slider("Select a value", 0, 100, 50)
 
if value > 75:
    breakpoint()  # Only triggers when slider exceeds 75
    result = expensive_computation(value)
    st.write(result)

You can also use conditional breakpoints in VS Code: right-click a breakpoint and set a condition like value > 75.

VS Code Extensions for Streamlit Development

These extensions improve the Streamlit development workflow beyond the basics:

ExtensionDescriptionUse Case
Python (Microsoft)Core Python supportRequired for IntelliSense, debugging
Pylance (Microsoft)Fast type checking and auto-importsStreamlit API completions
Stlite (whitphx)In-editor Streamlit previewQuick previews without launching a server
Better CommentsColor-coded comment annotationsMarking TODO and FIXME in data scripts
autoDocstringGenerate docstrings from function signaturesDocumenting Streamlit callbacks
GitLensInline Git blame and historyTracking changes across team members

Using the Stlite Extension

The Stlite extension runs a WebAssembly version of Streamlit directly inside a VS Code panel, so you can preview your app without opening a browser:

  1. Install the "stlite" extension from the VS Code marketplace.
  2. Open the Command Palette (Ctrl+Shift+P / Cmd+Shift+P).
  3. Type "Launch stlite preview" and select the command.
  4. Choose your .py file.

The preview appears inside VS Code. Note that Stlite uses a WASM build of Python, so some libraries (like NumPy compiled with C extensions) may not work identically to the full CPython runtime. Use Stlite for quick layout checks and the full streamlit run command for testing data-heavy logic.

Common Errors and Fixes

"streamlit: command not found"

This is the most common issue. It means the terminal cannot locate the Streamlit executable.

Cause: The virtual environment is not activated, or VS Code is using a different Python interpreter than the one where Streamlit is installed.

Fix:

# Verify which Python is active
which python    # macOS/Linux
where python    # Windows
 
# If it points to the system Python, activate your venv
source .venv/bin/activate
 
# Confirm Streamlit is installed in this environment
pip show streamlit

Also verify VS Code's selected interpreter matches your virtual environment (bottom-left status bar).

ModuleNotFoundError: No module named 'streamlit'

Cause: Streamlit is installed in one environment, but VS Code runs the script with a different interpreter.

Fix: Open the Command Palette, select "Python: Select Interpreter," and choose the interpreter from your .venv. Then restart the terminal with Ctrl+Shift+` (backtick).

Import Resolution Errors in Pylance

Pylance may show yellow squiggly lines under import streamlit as st even when Streamlit is installed.

Fix: Add the virtual environment to Pylance's search paths in .vscode/settings.json:

{
    "python.analysis.extraPaths": [
        "${workspaceFolder}/.venv/lib/python3.11/site-packages"
    ]
}

Alternatively, restart the Pylance language server: open the Command Palette and run "Pylance: Restart Language Server."

Port 8501 Already in Use

Cause: A previous Streamlit process was not terminated.

Fix:

# Find the process using port 8501
lsof -i :8501           # macOS/Linux
netstat -ano | findstr 8501   # Windows
 
# Kill the process
kill -9 <PID>           # macOS/Linux
taskkill /PID <PID> /F  # Windows

Or run Streamlit on a different port: streamlit run app.py --server.port 8502.

Breakpoints Not Triggering

Cause: Using "type": "python" instead of "type": "debugpy" in launch.json, or the debugger attaches to the wrong process.

Fix: Ensure your launch.json uses "type": "debugpy" and "module": "streamlit" (not "program"). Streamlit forks a separate file-watcher process; the debugger must attach to the main process that runs your script.

Hot Reload and Live Preview

Streamlit watches your source files and reruns the script when it detects changes. This hot reload behavior is one of its key advantages for rapid development.

How Auto-Reload Works

When you save a file, Streamlit detects the filesystem change and re-executes the entire script from top to bottom. The browser updates automatically. This means:

  • Variable assignments reset on each rerun.
  • Use st.session_state to preserve state across reruns.
  • Expensive computations should be wrapped in @st.cache_data or @st.cache_resource to avoid recalculating on every change.
import streamlit as st
import pandas as pd
 
@st.cache_data
def load_data(path):
    """Cached to prevent reloading on every interaction."""
    return pd.read_csv(path)
 
data = load_data("large_dataset.csv")
st.dataframe(data)

When Auto-Reload Does Not Work

Hot reload does not detect changes in:

  • Imported modules that are cached by Python's import system. Use importlib.reload() during development or restart the Streamlit server.
  • Files outside the project directory.
  • Environment variable changes.

You can force a full rerun by clicking "Rerun" in the Streamlit app's top-right menu or pressing "R" in the browser.

Configuring Reload Behavior

In .streamlit/config.toml:

[server]
runOnSave = true
fileWatcherType = "auto"

Set fileWatcherType = "poll" if you work inside Docker containers or remote filesystems where inotify events are unreliable.

Deploying Streamlit Apps

Once your app works locally in VS Code, you can deploy it to make it accessible to others. Here is a comparison of popular hosting options:

PlatformFree TierCustom DomainDocker SupportBest For
Streamlit Community CloudYesNoNoQuick sharing, open-source projects
RailwayLimitedYesYesSmall teams, auto-deploys from Git
RenderYes (750 hrs/mo)YesYesProduction apps with scaling
HuggingFace SpacesYesNoYesML demos and model showcases
AWS/GCP/AzurePay-as-you-goYesYesEnterprise production workloads

For detailed deployment instructions, see our dedicated guide: How to Deploy a Streamlit App.

All platforms require a requirements.txt file listing your dependencies. Some also require a Procfile or Dockerfile for custom startup commands.

Visualize Data with PyGWalker in Streamlit

When building data applications, you often need more than static charts. PyGWalker (opens in a new tab) is an open-source Python library that embeds a Tableau-like interactive visualization interface directly into your Streamlit app. Users can drag and drop fields, switch chart types, and filter data without writing additional code.

import streamlit as st
import pygwalker as pyg
import pandas as pd
 
st.set_page_config(page_title="Data Explorer", layout="wide")
st.title("Interactive Data Explorer")
 
uploaded_file = st.file_uploader("Upload a CSV file", type="csv")
 
if uploaded_file is not None:
    df = pd.read_csv(uploaded_file)
    st.write(f"Dataset: {df.shape[0]} rows, {df.shape[1]} columns")
    pyg.walk(df, env="streamlit", dark="auto")
else:
    # Demo with sample data
    df = pd.DataFrame({
        "Region": ["North", "South", "East", "West"] * 25,
        "Sales": [round(x * 1.5, 2) for x in range(100)],
        "Category": ["Electronics", "Clothing", "Food", "Books"] * 25
    })
    pyg.walk(df, env="streamlit", dark="auto")

PyGWalker turns your Streamlit app into a self-service analytics tool. This is particularly useful when building internal dashboards where stakeholders need to explore data without asking the engineering team to create new charts.

For data scientists working across Jupyter notebooks and Streamlit, RunCell (opens in a new tab) provides an AI agent that operates directly inside Jupyter, helping you prototype data transformations and visualizations before moving them into production Streamlit apps.

FAQ

How do I install Streamlit in VS Code?

Open the VS Code integrated terminal (Ctrl+Shift+or Cmd+J), create and activate a virtual environment withpython -m venv .venvfollowed bysource .venv/bin/activate(macOS/Linux) or.venv\Scripts\activate(Windows), then runpip install streamlit. Select the virtual environment as your Python interpreter through the Command Palette (Ctrl+Shift+P, then "Python: Select Interpreter"). Verify the installation by running streamlit version` in the terminal.

How do I run a Streamlit app from VS Code?

Open the integrated terminal in VS Code, make sure your virtual environment is activated, and run streamlit run your_script.py. The app launches at http://localhost:8501 (opens in a new tab) by default. You can specify a custom port with --server.port 8502 or prevent automatic browser launch with --server.headless true. For debugging, use the VS Code debugger with a launch.json configuration that sets "module": "streamlit" and passes ["run", "your_script.py"] as args.

Why does VS Code say "streamlit not found" even after installation?

This happens when the VS Code terminal uses a different Python environment than the one where Streamlit is installed. Check the Python interpreter shown in the VS Code status bar (bottom-left). If it points to the system Python instead of your virtual environment, press Ctrl+Shift+P, select "Python: Select Interpreter," and choose the interpreter inside your .venv folder. Then open a new terminal instance for the change to take effect.

How do I debug a Streamlit app with breakpoints in VS Code?

Create a .vscode/launch.json file with a configuration that uses "type": "debugpy", "request": "launch", and "module": "streamlit" with args ["run", "${file}"]. Set breakpoints by clicking in the gutter next to line numbers, then press F5 to start debugging. The app runs in the integrated terminal, and VS Code pauses execution at breakpoints where you can inspect variables, evaluate expressions, and step through code.

Does Streamlit auto-reload when I save files in VS Code?

Yes. Streamlit watches your source files and reruns the script automatically when you save changes. The browser refreshes to show updated output. This hot reload works for the main script and directly imported local modules. If auto-reload stops working, check that runOnSave = true is set in .streamlit/config.toml and that the file watcher type is compatible with your filesystem. Inside Docker or remote environments, set fileWatcherType = "poll" for reliable change detection.

Conclusion

A properly configured VS Code environment transforms Streamlit development from a trial-and-error process into a smooth workflow with auto-complete, inline debugging, and instant hot reload. The key steps are: isolate dependencies with a virtual environment, set the correct Python interpreter in VS Code, configure launch.json for debugger support, and install extensions like Pylance for type-aware IntelliSense.

Most "Streamlit not working in VS Code" issues trace back to interpreter mismatches between the terminal and the installed packages. Once you verify that VS Code, the terminal, and the debugger all point to the same .venv, the remaining setup is straightforward.

Related guides you may find useful:

📚