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:
| Requirement | Minimum Version | How to Verify |
|---|---|---|
| Python | 3.9+ | python --version |
| pip | 21.0+ | pip --version |
| VS Code | 1.80+ | code --version |
| VS Code Python Extension | Latest | Check 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 .venvActivate the environment:
# macOS / Linux
source .venv/bin/activate
# Windows (PowerShell)
.venv\Scripts\Activate.ps1
# Windows (Command Prompt)
.venv\Scripts\activate.batOption 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 # WindowsOption C: Using Conda
If you work within the Anaconda or Miniconda ecosystem:
conda create -n streamlit-env python=3.11
conda activate streamlit-envTell 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 streamlitVerify the installation:
streamlit versionYou 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.0Then install from the file:
pip install -r requirements.txtStep 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.pyStreamlit 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:8501Specifying a Custom Port
If port 8501 is occupied, specify a different port:
streamlit run app.py --server.port 8502Disabling Automatic Browser Launch
To prevent the browser from opening automatically each time:
streamlit run app.py --server.headless trueYou can make this permanent by creating .streamlit/config.toml in your project:
[server]
headless = true
port = 8501
[browser]
gatherUsageStats = falseStep 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:
| Extension | Purpose | Publisher |
|---|---|---|
| Black Formatter | Auto-format on save | Microsoft |
| Pylint or Ruff | Catch errors and enforce style | Microsoft / Astral |
| Pylance | Fast IntelliSense and type checking | Microsoft |
Ruff is a modern alternative to Pylint that runs significantly faster and combines linting with formatting in a single tool:
pip install ruffDebugging 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
- Open your Streamlit script in VS Code.
- Click in the gutter to the left of a line number to set a breakpoint (a red dot appears).
- Press F5 or click "Run and Debug" in the sidebar.
- Select the "Debug Streamlit" configuration.
- 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:
| Extension | Description | Use Case |
|---|---|---|
| Python (Microsoft) | Core Python support | Required for IntelliSense, debugging |
| Pylance (Microsoft) | Fast type checking and auto-imports | Streamlit API completions |
| Stlite (whitphx) | In-editor Streamlit preview | Quick previews without launching a server |
| Better Comments | Color-coded comment annotations | Marking TODO and FIXME in data scripts |
| autoDocstring | Generate docstrings from function signatures | Documenting Streamlit callbacks |
| GitLens | Inline Git blame and history | Tracking 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:
- Install the "stlite" extension from the VS Code marketplace.
- Open the Command Palette (Ctrl+Shift+P / Cmd+Shift+P).
- Type "Launch stlite preview" and select the command.
- Choose your
.pyfile.
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 streamlitAlso 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 # WindowsOr 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_stateto preserve state across reruns. - Expensive computations should be wrapped in
@st.cache_dataor@st.cache_resourceto 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:
| Platform | Free Tier | Custom Domain | Docker Support | Best For |
|---|---|---|---|---|
| Streamlit Community Cloud | Yes | No | No | Quick sharing, open-source projects |
| Railway | Limited | Yes | Yes | Small teams, auto-deploys from Git |
| Render | Yes (750 hrs/mo) | Yes | Yes | Production apps with scaling |
| HuggingFace Spaces | Yes | No | Yes | ML demos and model showcases |
| AWS/GCP/Azure | Pay-as-you-go | Yes | Yes | Enterprise 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:
- How to Run Streamlit -- startup options and CLI flags
- Deploy a Streamlit App -- production deployment walkthrough
- Streamlit Dashboard Tutorial -- building interactive dashboards
- Streamlit Session State -- managing state across reruns
- Streamlit Caching -- performance optimization with cache decorators