VSCode does not update environment variables upon .env modification

1.1k views Asked by At

I'm using .env in a Python project, with python-dotenv, but it seems like VSCode automatically loads the environment variables from the .env.

Unfortunately, VSCode does not seem to update the environment variables when I modify the .env file, causing the Python program to run on old environment vars.

Restarting VSCode / opening new integrated terminals does not seem to help. It looks as if it caches the .env somewhere, and reloads it from cache, without removing the cache when the original file is updated.

Output of /usr/bin/env together with .env file:

enter image description here

Output of Help: About:

Version: 1.84.0-insider (Universal)
Commit: f1c3b1dcf85e3b6ddb24b7dce0e4b122e8ce6233
Date: 2023-10-17T05:38:23.658Z
Electron: 25.8.4
ElectronBuildId: 24154031
Chromium: 114.0.5735.289
Node.js: 18.15.0
V8: 11.4.183.29-electron.0
OS: Darwin x64 22.6.0

Python extension version v2023.19.12931008.

2

There are 2 answers

1
Sean K. On

I'm not sure how your Python code is getting environment variables, but this is how I usually do.

.env

BROADCAST_MAC=ff:ff:ff:ff:ff:ff
DEFAULT_MAC=11:22:33:44:55:66

config.py

from dotenv import load_dotenv
from pathlib import Path
import os

# path to your .env file
env_path = Path(".") / ".env"
load_dotenv(dotenv_path=env_path)

class Config: # Save your var in a class
    BROADCAST_MAC = os.getenv("BROADCAST_MAC")
    DEFAULT_MAC = os.getenv("DEFAULT_MAC")

main.py

import config

BROADCAST_MAC = config.Config.BROADCAST_MAC
DEFAULT_MAC = config.Config.DEFAULT_MAC

I personally like separated file for configurations (easier to debug). Let me know if this helped, if not, this might help

1
bleg On

Came accross same issue today. It really looks like VSCode caches values somewhere, and pre-initializes the terminal with environment from cached (outdated .env). The workaround is to use override=True in load_dotenv(). Surely, looks like a bug.