简体   繁体   中英

Enviroment variables in pyenv-virtualenv

I have created a virtual environment with pyenv virtualenv 3.5.9 projectname for developing a django project.

How can I set environment variables for my code to use?

I tried to add the environment variable DATABASE_USER in /Users/developer/.pyenv/versions/projectname/bin/activate like this:

export DATABASE_USER="dbuser"

When I tried to echo $DATABASE_USER an empty string gets printed.

Tried to install zsh-autoenv

And now I can echo $DATABASE_USER and get the value set in the .autoenv.zsh file.

But I can't seem to get the environment variable to be available to my django code:

If I try to os.getenv('DATABASE_USER', '') in the python shell inside the virtualenv, I get ''

What could be wrong? Is the zsh-autoenv variables just available for the zsh shell and not python manage.py shell ?

I was wondering a similar thing, and I stumbled across a reddit thread where someone else had asked the same question, and eventually followed up noting some interesting finds.

As you noticed, pyenv doesn't seem to actually use the bin/activate file. They didn't say what the activation method is, but like you, adding environment variables there yielded no results.

In the end, they wound up installing autoenv , which bills itself as directory-based environments. It allows you to create an .env file in your directory, and when you cd to that directory, it runs the .env file. You can use it for environment variables, or you could add anything else to it.

I noticed on the autoenv page that they say you should probably use direnv instead, as it has better features and is higher quality software. Neither of these are Python or pyenv specific, and if you call your python code from outside of the directory, they may not work. Since you're using pyenv, you're probably running your code from within the directory anyway, so I think there's a good chance either one could work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM