(Solution found) VS Code integrated Run and Debug

Hello everyone,

My interpreter was not correctly pointing to python in my venv … yeah rookie mistake.

I have a small script in development that involves creating a dashboard with Streamlit. The project is currently not deployed; it’s local. The whole code is at the end (st.title and database_path are removed for my own reasons)

I’m using VS Code with a virtual environment (venv) that I named ‘.dashboard_venv’. My venv is activated, and I’ve installed the following packages (copy-paste from requirements.txt):

altair==5.4.1
attrs==24.2.0
blinker==1.8.2
cachetools==5.5.0
certifi==2024.8.30
charset-normalizer==3.3.2
click==8.1.7
colorama==0.4.6
gitdb==4.0.11
GitPython==3.1.43
idna==3.10
Jinja2==3.1.4
jsonschema==4.23.0
jsonschema-specifications==2023.12.1
markdown-it-py==3.0.0
MarkupSafe==2.1.5
mdurl==0.1.2
narwhals==1.9.1
numpy==2.1.2
packaging==24.1
pandas==2.2.3
pillow==10.4.0
protobuf==5.28.2
pyarrow==17.0.0
pydeck==0.9.1
Pygments==2.18.0
python-dateutil==2.9.0.post0
pytz==2024.2
referencing==0.35.1
requests==2.32.3
rich==13.9.2
rpds-py==0.20.0
six==1.16.0
smmap==5.0.1
streamlit==1.39.0
tenacity==9.0.0
toml==0.10.2
tornado==6.4.1
typing_extensions==4.12.2
tzdata==2024.2
urllib3==2.2.3
watchdog==5.0.3

The application works perfectly when I run ‘streamlit run dashboard.py’ (my app is named ‘dashboard.py’).

The problem arises when I set breakpoints to debug my code, track values, call stack, etc. I receive the following message:

Exception has occurred: ModuleNotFoundError
No module named 'streamlit'
  File "FILE PATH REMOVED", line 4, in <module>
    import streamlit as st
ModuleNotFoundError: No module named 'streamlit'

I found previous posts discussing this issue. These posts suggested modifying the launch.json file, which I did:

{
    // 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": "${file}",
            "console": "integratedTerminal"
        }
        {
            "name": "Python: Streamlit",
            "type": "python",
            "request": "launch",
            "module": "streamlit",
            "args": [
            "run",
            "${file}",
            ]
        }
    ]
}

My code is as follow:

import numpy as np
import pandas as pd
import sqlite3
import streamlit as st

# Display TITLE
st.title("TITLE REMOVED")

##################################
#       DATABASE CONNECTION
##################################
DATABASE_PATH = 'FILE PATH REMOVED'

@st.cache_resource
def get_connection(db_path):
    """Establishes a connection to the database"""
    conn = sqlite3.connect(db_path)
    return conn

@st.cache_data
def get_table_names(_connection):
    """Retrieves the list of tables in the SQLite database."""
    query = "SELECT name FROM sqlite_master WHERE type='table'"
    cursor = _connection.execute(query)
    tables = [row[0] for row in cursor.fetchall()]
    return tables

@st.cache_data
def load_table_data(_connection, table_name):
    """Loads data from a specific table into a DataFrame."""
    query = f"SELECT * FROM {table_name}"
    df = pd.read_sql_query(query, _connection)
    return df

# Create the database connection and load all tables into DataFrames
conn = get_connection(DATABASE_PATH)

# Get the list of tables
try:
    tables = get_table_names(conn)
except sqlite3.Error as e:
    st.error(f"Error retrieving tables: {e}")
    st.stop()

# Load all tables into a dictionary of DataFrames
data_tables = {}
for table in tables:
    try:
        data_tables[table] = load_table_data(conn, table)
    except sqlite3.Error as e:
        st.error(f"Error retrieving data from table {table}: {e}")
        data_tables[table] = pd.DataFrame()  # Create an empty DataFrame in case of error

# Close the database connection after loading all data
# conn.close()

##################################
#          SIDEBAR
##################################
@st.cache_data
def get_seasons(data_tables):
    """Fetches the list of unique seasons from the 'teams' table."""
    if 'teams' in data_tables:
        return data_tables['teams']['season'].unique().tolist()
    return []

# @st.cache_data
def get_teams_name(data_tables, season):
    """
    Fetches all the teams' name from a specified season.

    Args:
    - data_tables (dict): A dictonary of Dataframes containging all the tables from the database.
    - season (str): The specified season.
    """
    if 'teams' in data_tables:
        filtered_teams = data_tables['teams'][data_tables['teams']['season'] == season]
        return data_tables['team_name'].unique().tolist()
    return []

# Retrieve the available seasons from the 'teams' table
seasons = get_seasons(data_tables)

# Sidebar for selecting the season
selected_season = st.sidebar.selectbox("Select a season", seasons)

teams = get_teams_name(data_tables, selected_season)

selected_team = st.sidebar.selectbox("Select the team", teams)


##################################
#          MAIN CONTENT
##################################
if tables:
    tabs = st.tabs(tables)
    
    for tab, table_name in zip(tabs, tables):
        with tab:
            st.header(f"Table: {table_name}")
            if not data_tables[table_name].empty:
                st.dataframe(data_tables[table_name])
            else:
                st.info("No data to display for this table.")
else:
    st.info("No tables found in the database.")

As you can see, I am not a professional developer, just a complete amateur. If you notice any aspects of my scripts that can be improved, I’m open to suggestions. But the priority is on getting the integrated run and debug from VS Code to work with Streamlit.