How to set environment variables in pyenv?
Asked Answered
G

1

7

I'm using pyenv. The environment is created with these commands:

pyenv install 3.6.0
pyenv virtualenv 3.6.0 foo
pyenv local foo

python my_app.py

In the application I want to load some environment variables with this command:

SOME_VARIABLE = environ.get('MY_ENV_VAR', None)

The problem is, that although MY_ENV_VAR is set with export MY_ENV_VAR=test (and I can display its content with echo $MY_ENV_VAR), the python code reads no value.

So how can this be done correctly?

Gamesmanship answered 25/5, 2018 at 16:5 Comment(2)
Can you compare echo $MY_ENV_VAR and python -c "import os; print(os.environ.get('MY_ENV_VAR'))"; do both print "test"?Palliative
@jasdhfiu-asef-aesf-asef-a-sgaa No I didn't, what should it do? I don't use pipenv. Didn't you mean pyenv shell? This gives "no shell-specific version configured". @Palliative echoing the variable returns its true content, priting it in python like this prints "None".Gamesmanship
D
0

What IDE/Editor are you using? I am guessing the variable is not added into the same environment.

If you use a code editor like vscode you need to activate the environment then from the same terminal add the variable to the environment and then run the script.

# my_app.py
from os import environ

SOME_VARIABLE2 = environ.get('MY_ENV_VAR',None)
print(SOME_VARIABLE2)

SOME_VARIABLE = environ['MY_ENV_VAR']
print(SOME_VARIABLE)
# vscode terminal

test on main [?] via 🐍 v3.8.6 (foo) 
❯source foo/bin/activate
❯export MY_ENV_VAR=test
❯ python my_app.py         
test
test


Debera answered 30/12, 2021 at 19:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.