Skip to content
Home ยป Set environment variables in a Python venv (Windows)

Set environment variables in a Python venv (Windows)

  • by
  • 1 min read

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.


Say thanks, ask questions or give feedback

Technologies get updated, syntax changes and honestly… I make mistakes too. If something is incorrect, incomplete or doesn’t work, let me know in the comments below and help thousands of visitors.

Leave a Reply

Your email address will not be published.