-2

How can I get my key in my .env file?

What's the problem in my code (macOS)? The dotenv works fine, but is it possible to use only the os module?

In the .env:

key = 123456

and in the test.py:

import os

actual_key = os.getenv('key')

print(actual_key)

Finally the output in console was:

None
Michael M.
  • 10,486
  • 9
  • 18
  • 34

3 Answers3

1

os.getenv('key') looks for 'key' in environmental variables. By default key-value pairs that are in .env file are not loaded into environment variables. If you want to load key this way you have to first add the contents of .env file to environment variables. I suggest using python-dotenv library:

import os
from dotenv import load_dotenv

load_dotenv() # will search for .env file in local folder and load variables 

KEY_VAR = os.getenv('KEY')
R.Lemiec
  • 61
  • 2
0

You need to use dotenv to load the environment variables from a .env file, like so:

from dotenv import load_dotenv

# Load the environment variables from the .env file
load_dotenv()

actual_key = os.getenv('key')
print(actual_key)

dotenv can be installed with pip install python-dotenv

linuxsushi
  • 151
  • 4
0

You cannot do what you want. The os.getenv cannot get variables straight from the .env file. TLDR;

Regarding the setting of the env vars:

In macOS to set the env var temporarily:

export [variable_name]=[variable_value]

To do it permanently:

  • open ~/.bash-profile
  • scroll down to the end of the .bash_profile file
  • add export [variable_name]=[variable_value] at the end of it
  • save any changes you made to the .bash_profile file
  • execute the new .bash_profile by either restarting the terminal window or using source ~/.bash-profile

If you don't want to use the mentioned dotenv library you'll have to source the .env file first and export all the variables before running your python script which uses os.getenv, see this: https://stackoverflow.com/a/65694371/15923186

Gameplay
  • 1,142
  • 1
  • 4
  • 16