I’m trying to set environment variables within a Python virtual environment in VS Code (mostly for API keys). The VS Code documentation here: https://code.visualstudio.com/docs/python/environments suggests that Python will automatically detect a .env file within a workspace folder. However, that doesn’t seem to be happening. When I enter the following code, the terminal returns a value of None.
import os
SHEETY_ENDPOINT = os.getenv("SHEETY_ENDPOINT")
SHEETY_TOKEN = os.getenv("SHEETY_TOKEN")
I’m using the dotenv package to make the code work right now, but don’t want to have to rely on it if it is unnecessary in a VS Code workspace.
3
Answers
In order for Python to automatically detect a
.env
file within a workspace folder, you need to ensure that you have the Python extension installed in VS Code. Once you have the extension installed, follow these steps:.env
in the root of the workspace folder..env
file in the following format:If you have followed these steps and are still unable to retrieve the environment variable values, then you may need to manually load the environment variables using the dotenv package or by setting them using your operating system’s environment variable settings.
If you are using the debugger to launch your python app, open the .vscode/launch.json at the project root, edit the envs in
env
, e.g.ref: https://code.visualstudio.com/docs/python/debugging
You can add
.env
file under workspace..env
Then add the following codes to your
settings.json
:Then use shortcuts F5 or Debug Python File so that you can get the environment variable stored in the
.env
file. You can also use interactive window which can work as well.