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

Set environment variables in a Python venv (Windows)

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.

5 thoughts on “Set environment variables in a Python venv (Windows)”

  1. I lovesd as mmuch as you’ll recive carrierd outt righbt here.

    Thee sketch is attractive, your auhored material stylish.
    nonetheless, yoou commasnd gget gott an shakiness ovcer that you
    wish be delivering the following. unhwell unquestionably come further formerly again as exaxtly thee same
    nearly vry often insid casse you shield this increase.

Leave a Reply

Your email address will not be published. Required fields are marked *