Monkey Pylot
Monkey Pylot

Reputation: 142

Set environment variables when activating python virtual environment in windows

I want to be able to set up environment variables in my virtual environment so that they are available in my code when I activate the virtual environment. I make my virtual enviornments with venv. I'm working on a Windows machine with VS-code.

What I already tried, but didn't work.

  1. Adding the vars to end of the activate.bat file like this:
set CLIENT_SECRET="MYSECRET"
  1. Adding the vars to the end of the Activate.ps1 file like this:
$CLIENT_SECRET="MYSECRET"
  1. Adding the vars to the end of the activate file like this:
export CLIENT_SECRET="MYSECRET"

I found a lot related to my topic, but none working for me. What to do?

Upvotes: 4

Views: 13820

Answers (5)

blokeish
blokeish

Reputation: 601

The default Terminal that popped up for me in VS Code was the PowerShell, which I didn't realize at first. I had to use:

To write the env variable

$Env:MYAPP_DB_USER = "myapp_user"

To read the env variable

$Env:MYAPP_DB_USER

NB: '$' in front is part of the command. 'MYAPP_DB_USER' is the Key and 'myapp_user' is the Value I don't want to keep the passwords and keys as part of the code (including .env file) and have it pushed to the git repo and the server.

Ref: Microsoft PowerShell - Env variables

Upvotes: 2

Raoul Zachary
Raoul Zachary

Reputation: 1

use set in CMD teminal

use env: in powershell

Upvotes: 0

ashish bindra
ashish bindra

Reputation: 59

go to endowment variable folder enter Script folder now activate with cmd

Upvotes: 0

makozaki
makozaki

Reputation: 4366

If you want to setup your development environment in VSCode you can simply add .env file with all secrets defined in project root directory. More details in docs

Upvotes: 7

jorop
jorop

Reputation: 533

Your first solution

set CLIENT_SECRET=MYSECRET

in activate.batshould work, when using Command Prompt in the terminal as Default Shell.

You can omit the quotes unless they are part of your envirionment variable.

You can verify, if the environment variable is set with:

echo %CLIENT_SECRET% in the terminal in VS-Code.

Upvotes: 2

Related Questions