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 ?

Krowar
  • 341
  • 2
  • 7
  • 15
  • 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. – Barmar Jan 21 '23 at 23:28
  • See this as well https://stackoverflow.com/questions/19070615/python-os-getenv-and-os-environ-dont-see-environment-variables-of-my-bash-she – Majiick Jan 21 '23 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' – Krowar Jan 21 '23 at 23:50
  • run the script by hand from a terminal, rather than using Pycharm's console. – Barmar Jan 22 '23 at 00: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). – Kurtis Rader Jan 22 '23 at 18:55
  • Or you can configure your "run configuration", set the envvar there. – Lenormju Jan 23 '23 at 07:30

1 Answers1

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')
Krowar
  • 341
  • 2
  • 7
  • 15