9

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Vaibhav
  • 507
  • 2
  • 4
  • 20
  • 1
    What do you mean to tell us by `vim .env`? – mkrieger1 Jul 11 '20 at 22:41
  • 2
    Also this is not really a Python problem. If the environment variable exists, it can be accessed by Python, or any other program. – mkrieger1 Jul 11 '20 at 22:43
  • @mkrieger1 Agreed. I didn't want to get the .profile populated with custom env variables. I've found a way for Unix operating systems and I've added my answer. – Vaibhav Jul 12 '20 at 10:06

3 Answers3

9

You can source it before running it:

$ source .env
$ python
>>> import os
>>> os.environ['token_id']
chehsunliu
  • 1,559
  • 1
  • 12
  • 22
3

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.

Vaibhav
  • 507
  • 2
  • 4
  • 20
0

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.

Jeff
  • 856
  • 7
  • 13