Here's one of those rare questions that gets asked a lot on SO, but there's no answer. I'll ask it again a little differently.
I'm trying to set an environment variable using a file and then read the variable in python. That should be pretty basic.
However, check this out:
$ cat .env.test
NAME=Bob
$ cat x.py
import os
print(os.environ.get("NAME"))
$ (source .env.test; echo $NAME)
Bob
$ (source .env.test; python3 x.py)
None
Isn't that strange? Why doesn't it work?
Is it because I didn't write export
in the .env file? If I add export
, it does work. But why? Isn't this what source
is supposed to do?
$ cat .env.test
export NAME=Bob
$ cat x.py
import os
print(os.environ.get("NAME"))
$ (source .env.test; echo $NAME)
Bob
$ (source .env.test; python3 x.py)
Bob
I think the community could use an explanation about how sub-shells work, how source
works and where python is looking for the environment variables, to answer this once and for all. Can you do that?
Related Questions