Forums

Environment variables not being read from .env after CMD+Shift+H shortcut attempt from console

I am using Chrome (version 103.0.5060.114) on MacOS Monterey (version 12.4).

I've been running a Python script without any problems. It is not a web app -- it's just a collection of three modules.

Earlier today, I attempted to navigate away from my console using the CMD+Shift+H shortcut. Nothing happened. My script was not running. I tried to run my script again:

$ python3 myscript.py

But the compiler suddenly tells me that an environment variable couldn't be read.

MY_ENV_VAR = os.environ['key']

raise KeyError(key) from None

I was able to successfully run my script without issue prior to attempting the CMD+Shift+H shortcut. I tried creating a new console and clearing my cache in Chrome.

In the new console, I ran the following: $ echo "export MY_ENV_VAR=my_env_var_value" >> .env

But $ printenv does not display MY_ENV_VAR

Additionally, my .env file contains the following:

export MY_ENV_VAR=my_env_var_value

I tried manually adding quotes around the value in .env like so: export MY_ENV_VAR="my_env_var_value" but this did not work. I also tried deleting .env and repeating the instructions in the documentation.

All of my files are in the same directory. How can I get bash to read my environment variable?

If you're running in a console, you'll need to tell it explicitly to load up the contents of your .env file. Files with names like that are not automatically loaded. The Bash syntax to load one is:

source .env

The instructions on the page you linked to also give a useful way to run that source command whenever you activate a virtualenv, but again, those won't be automatically run when you start a fresh bash console; you'll need to activate the env.