theskumar / python-dotenv

Reads key-value pairs from a .env file and can set them as environment variables. It helps in developing applications following the 12-factor principles.
https://saurabh-kumar.com/python-dotenv/
BSD 3-Clause "New" or "Revised" License
7.66k stars 430 forks source link

easily allow sourcing .env-file in bash #487

Open woutervh opened 1 year ago

woutervh commented 1 year ago

python-dotenv is a python-library, and used in python-code. Currently .env-files can only contain:

But sometimes, env-vars are also used by executables outside your python-code. E.g In a django-project with a postgresql-backend, I have these env-vars:

# postgres - used in django-settings + by postgres-executables (pg_* )
PGHOSTADDR="127.0.0.1"
PGPORT="5432"
PGDATABASE="my-db"
PGUSER="my-dbadmin"
PGPASSWORD="SUPERSECRET"
PGOPTIONS=""

# used only by postgres-executables, 
# cfr. https://www.postgresql.org/docs/12.1/libpq-envars.html
PGDATA="..."
PGHOST="..."

I use following snippet to load all these key/value-pairs in my current bash-session to use the postgresql-commands: `

set -a && source .env && set +a `

You can find many oneliners to source a .env-file in bash, many using grep/sed/xargs/...

If we would allow setting bash-options in the .env-file:

set -o allexport
PGHOSTADDR="127.0.0.1"
...
set -o allexport

these option-lines can just be skipped in the python-parsing of the dotenv, this would simplify to:

 > source .env

just source the .env!

bbc2 commented 1 year ago

As documented in our readme (https://github.com/theskumar/python-dotenv#file-format), you may prepend export to your lines defining variables. Would that work for you?

There are several ways to do this in Bash and I'm not sure we want to add support for all the cases in Python-dotenv (i.e. ignore all possible forms of the "export" directives).

woutervh commented 1 year ago

ignore all possible forms of the "export" directives

ÌMHO, only needed is to skip/ignore lines starting with :

set -o ...
set +o ...

no?