Search code examples
pythonvisual-studio-codeenvironment-variables

How to set environment variables in python when using vscode


In vscode I have a project structure (using Windows):

  • venv
  • .env
  • test_load_env.py

My .env file contains:

PYTHONPATH=.
MY_USERNAME=myusername
MY_PASSWORD=mypass

test_load_env.py:

import os

username = os.environ.get("MY_USERNAME")
password = os.environ.get("MY_PASSWORD")
print(f"username: {username}, password: {password}")
print(os.environ.get("PYTHONPATH"))

Using vscode 1.84.2 the .env file is not imported automatically as running test_load_env.py returns:

username: None, password: None
None

Adding

"python.envFile": "${workspaceFolder}/.env",

to settings.json makes no difference. However, if I run as Debug Python File, then the environment variables are loaded correctly (even without the settings.json edit).

If I run the exact same project on vscode insiders (1.85.0), the environment variables are loaded correctly (without having to run as debug or edit settings.json).

My settings are identical between vscode and vscode insiders - why does vscode insiders import the environment variables as expected, but vscode doesn't?

Is my only solution under the release version of vscode is to use python-dotenv?

Thanks


Solution

  • It looks like this has been an issue in vscode for a while:

    https://github.com/microsoft/vscode-python/issues/944

    I think the solution is to add:

    "python.experiments.optInto": ["pythonTerminalEnvVarActivation"]
    

    into the user settings.json

    .env then gets loaded by vscode when running code (not just debug).

    Hopefully this helps someone.