This is a brief overview of the possibilities for setting environment variables in a virtual environment (venv).
Set environment variables in Python code
Environment variables can be set inside your Python script. All child processes will inherit the environment variables and their values.
import os os.environ['COMPOSER'] = 'Tchaikovsky'
Set environment variables in activate.bat or activate.ps1
If you want to set environment variables each time the venv is started, you can assign them inside the activation script. If you’re running a PowerShell terminal, you should edit Activate.ps1 in <YOUR_ENV>/Scripts and add an extra line to set an environment variable as follows.
$env:COMPOSER = 'Rachmaninov'
If you’re running a Windows command prompt, edit activate.bat in <YOUR_ENV>/Scripts and add the following line.
set COMPOSER = 'Stravinsky'
The key-value .env file in Visual Studio Code
VS Code automatically searches for an .env file. In this file, you can specify key-value pairs that are loaded as environment variables.