Setting Environment variables in .venv


I am using .venv to create a virtual environment to use for a project. Within this project, I need to access the OpenAI GPT3 environment. For this, i have an API key, but I want to store it as an environment variable. Because I use windows and VS-Code to work on my project, a lot of attempts have already failed. Does anyone have an idea how to solve this?

Asked By: Fabian



Remove the export command and set your key with

Answered By: Max

You can modify the system environment in the settings.json file like this:

  "": {
    "OPENAI_API_KEY": "xxx"

And add this in the .env file:


When the terminal settings are used, PYTHONPATH affects any tools that
are run within the terminal by a user, as well as any action the
extension performs for a user that is routed through the terminal such
as debugging. However, in this case when the extension is performing
an action that isn’t routed through the terminal, such as the use of a
linter or formatter, then this setting will not have an effect on
module look-up.

When PYTHONPATH is set using an .env file, it will affect anything the
extension does on your behalf and actions performed by the debugger,
but it will not affect tools run in the terminal.

You can refer to the official docs for more detail.

Answered By: Steven-MSFT

I have added the line OPENAI_API_KEY=xxxxxxx at the end of activate.bat file. The path is .venvScriptsactivate.bat.
I’m using Windows 11, VS Code, Powercell (terminal). After the virtual environment is activated in the terminal I’ve checked and the environment variable is echoed.


When I execute the python script (without importing os to set environment variable) the OPENAI_API_KEY environment variable is accessible to the code.

Hope this helps!

Answered By: nayak