Updated environment variable but os.getenv() keeps returning None [closed]
Asked Answered
S

2

48

I can't seem to get my code to respond to custom environment variables so I wrote a piece of code to test it. os.getenv is not pulling the environment variables that I've set in BASH into my Python code.

$ FRUSTRATION="PYTHON!!"
$ echo $FRUSTRATION
PYTHON!!
$ ipython
In [1]: import os

In [2]: very_frustrated = os.getenv("FRUSTRATION")

In [3]: print(very_frustrated)
None
Sized answered 21/11, 2016 at 19:54 Comment(7)
This is not the code you ran. echo FRUSTRATION without a leading $ would repeat FRUSTRATION, not the contents of the variable. At a guess, you didn't actually export FRUSTRATION in the shell you launched ipython from.Coz
Can't recreate this. Are you launching ipython from the same shell?Vocable
Which operating system / shell? That doesn't look like any linux shell I know of.Nabors
In many linux shells, !! is a shortcut for the previous command. If you simply meant it for emphasis, a different method would be good.Nabors
Had a similar issue within Jupyter notebook. Just had to restart Jupyter (not just the kernel).Selfaggrandizement
The issue is that the environment variable wasn't exported. You just need to write: export FRUSTRATION="PYTHON!!" and it will work. This is a duplicate of python - os.getenv and os.environ don't see environment variables of my bash shell.Dupery
It can be that you set the variable in a different shell. For example setting the variable in zsh and then running the python script from bash the variable won't show up in os.environVeasey
S
24

Works for me:

:: export FOO=boo
:: python
Python 2.7.10 (default, Jul 30 2016, 18:31:42)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.getenv('FOO')
'boo'
>>>

My guess is that you either forgot to export the variable, or you spelled the variable wrong.

Schorl answered 21/11, 2016 at 20:7 Comment(0)
S
15
print os.environ

Do this to see if you have environment var added to you system or not. Your python code is fine. It's the problem setting env var.

Sabinasabine answered 21/11, 2016 at 20:2 Comment(2)
I don't see how this is any better than just calling os.getenv. If its a problem setting the variable, this change doesn't help.Nabors
@Nabors It would show the variables you could see, and potentially see the variable you're looking for--except the name might be spelled wrong or something of that nature. I happen to think it is a valuable debugging step, but it's not a real answer to the problem.Schorl

© 2022 - 2024 — McMap. All rights reserved.