skip to Main Content

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

2

Answers


  1. You can use debug mode or interactive window which will read .env file.

    You can refer to this table about using .env and launch.json settings:

    Run option .env setting launch.json setting
    Run Python file in terminal no no
    Run in interactive Window yes no
    Debug via F5 yes yes
    "Debug Python File" (*) yes no

    You can also read document for more details about environment variables.

    Login or Signup to reply.
  2. from decouple import config
    
    class Settings(BaseSettings):
        ...
        JWT_SECRET_KEY: str = config("JWT_SECRET_KEY", cast=str)
        ...
    
    

    No configuration needed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search