44

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
Christopher Peisert
  • 21,862
  • 3
  • 86
  • 117
aselya
  • 537
  • 2
  • 5
  • 9
  • 4
    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. – ShadowRanger Nov 21 '16 at 20:00
  • Can't recreate this. Are you launching `ipython` from the same shell? – Dimitris Fasarakis Hilliard Nov 21 '16 at 20:00
  • Which operating system / shell? That doesn't look like any linux shell I know of. – tdelaney Nov 21 '16 at 20:01
  • 2
    In many linux shells, `!!` is a shortcut for the previous command. If you simply meant it for emphasis, a different method would be good. – tdelaney Nov 21 '16 at 20:04
  • Had a similar issue within Jupyter notebook. Just had to restart Jupyter (not just the kernel). – DonCarleone Apr 21 '21 at 17:04
  • 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](https://stackoverflow.com/q/19070615/1164465). – Christopher Peisert Jul 07 '22 at 15:53
  • 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.environ – shisui Jan 06 '23 at 04:02

2 Answers2

23

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.

John Szakmeister
  • 44,691
  • 9
  • 89
  • 79
13
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.

BufBills
  • 8,005
  • 12
  • 48
  • 90
  • 1
    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. – tdelaney Nov 21 '16 at 20:05
  • 11
    @tdelaney 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. – John Szakmeister Nov 21 '16 at 20:08