Is there any way to read .env files in macOS?

Viewed 12756

I created the .env file using the command and created variables like token_id="13423edq234" and so on. I don't want to use an external package like dotenv to read the file. I just want to know if there's any way to load the .env file that I've created so that it can be read by Python. Also I don't want to add the env variable to zprofile.

vim .env

and in the Python 3 shell,

import os
os.environ['token_id']

and it says, it's not defined.

4 Answers

You can source it before running it:

$ source .env
$ python
>>> import os
>>> os.environ['token_id']

Main criteria for searching for a solution is to not populate the .profile or .bash etc files with custom environment variables. I've found a solution that works quite well for me.

direnv is a package that I came across. It works with Unix based OS. Since I use a mac with zsh shell, it works amazing. Here's the link to install direnv.

After you follow the installation instructions, create a .envrc file and write your custom env variables, in my case, it would be like this in the .envrc file.

export token_id="13423edq234"

The best part is that it loads and unloads the variables automatically so your .profile stays clean. Let me know if you have any doubts.

Like @Vaibhav, I use direnv with the following .envrc file:

[ -f secrets ] && eval $(cat secrets | sed 's/^/export /') || echo "no secrets file"

Then you can have a secrets file (or call it .env if you like and update the .envrc file accordingly):

MY_ENV_VAR1 = foo
MY_ENV_VAR2 = bar

The sed part of the .envrc allows you to optionally include the export statement in the secrets/.env file.

Related