简体   繁体   中英

Run .env file in django app with python-dotenv when starting shell

I'm trying to use python-dotenv to run the .env file when running ./manage.py shell .

But .env isn't run when I start shell. Nothing different than normal happens.

What I've done:

  1. installed python-dotenv with pip install python-dotenv in my virtual environment
  2. added a .env file in the same directory as my project settings.py

Also added below to settings.py :

from dotenv import load_dotenv
load_dotenv()

For context, my .env looks like:

export PYTHONSTARTUP=`pwd`/.pythonrc.py
echo "environment variables set"

And I'm exporting .pythonrc.py so I can do some imports when shell is loaded.

I'm pretty new to django. Am I missing something obvious?

The problem is that you treat the env file as a shell one.

python-dotenv readme states that you can use export in your .env file, which is ignored by the package. This so that the env vars could alternatively be set by calling source .env from shell.

However, you can't run shell scripts that way. When I tried to load your example, I got this message:

Python-dotenv could not parse statement starting at line 2
True

After removing the echo line, I got just True as a response and PYTHONSTARTUP was set.

There's another issue, however, as you depend on shell scripting in the value of PYTHONSTARTUP as well. It's set to

'PYTHONSTARTUP': '`pwd`/.pythonrc.py'

Not what you'd expect. This should work:

export PYTHONSTARTUP2=${PWD}/.pythonrc.py

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