0

In the terminal, I have exported my API key the following way:

export ALPHAVANTAGE_KEY=XXXXXXXXXX 

In the console, when I type 'env' I get amongst other things :

ALPHAVANTAGE_KEY=XXXXXXXXXX 

But in my code, the following prints 'None' :

print(os.environ.get('ALPHAVANTAGE_KEY')) 

Why is that ?

6
  • 5
    Did you start the python process from the same shell where you exported the environment variable, after setting it? Environment inheritance happens when a child process is created. Commented Jan 21, 2023 at 23:28
  • See this as well stackoverflow.com/questions/19070615/… Commented Jan 21, 2023 at 23:29
  • I have created the env variable from Pycharm Terminal and then ran the program via Pycharm. Is that not ok ? Also I've tried to test what happens if I close pycharm and re-open it but in that case the variable disappears from the list when I check with 'env' Commented Jan 21, 2023 at 23:50
  • run the script by hand from a terminal, rather than using Pycharm's console. Commented Jan 22, 2023 at 0:09
  • Env vars are not global. They are per-process and when a process (like your shell or pycharm) starts another process it usually gives the new process a copy of its env vars. So changing the env vars in a shell does not affect the env vars of a different process (e.g., pycharm). Commented Jan 22, 2023 at 18:55

1 Answer 1

2

A nice way to manage the environment variables is with dotenv:

from dotenv import load_dotenv # pip install python-dotenv load_dotenv("/Users/gerald/environment_variables/.env") 

With the .env file looking like this :

ALPHAVANTAGE_KEY="XXXXXXXXXXXXX" NEWSAPI_KEY="YYYYYYYYYYYYY" 

And then use the values this way :

"apikey": os.environ.get('NEWSAPI_KEY') 
Sign up to request clarification or add additional context in comments.

Comments