Updated environment variable but os.getenv() keeps returning None

Question:

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
Asked By: aselya

||

Answers:

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.

Answered By: BufBills

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.

Answered By: John Szakmeister
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.