-1

I am trying to access environment variables using python and I don't know which function should I use os.getenv or os.environ.get?

Already referred : Difference between os.getenv and os.environ.get

I have enviroment variables like this and want to use them so which function mentioned above will be preferable?

USERNAME=johndoe
PASSWORD=johndoepass
rhoitjadhav
  • 691
  • 7
  • 16
  • I'm pretty sure they are equivalent. Unfortunately, that other question has an incorrect answer as the accepted answer... – juanpa.arrivillaga May 01 '19 at 17:39
  • @Chris neither raises an exception. `dict.get` returns `None` if the key does not exist. Indeed, I believe `os.getenv` is just a convenience function implemented as `os.environ.get(key)` – juanpa.arrivillaga May 01 '19 at 17:42
  • @juanpa.arrivillaga That is [literally](https://github.com/python/cpython/blob/3.7/Lib/os.py#L769) the case. – chepner May 01 '19 at 17:47

1 Answers1

4

Use os.environ, not because of any functional difference, but because os.putenv is broken and using os.getenv will encourage you to use os.putenv.

os.putenv updates the actual OS-level environment variables, but in a way that isn't visible through os.getenv, os.environ, or any other stdlib way of inspecting environment variables:

>>> import os
>>> os.environ['asdf'] = 'fdsa'
>>> os.environ['asdf']
'fdsa'
>>> os.putenv('aaaa', 'bbbb')
>>> os.getenv('aaaa')
>>> os.environ.get('aaaa')
user2357112
  • 260,549
  • 28
  • 431
  • 505
  • 1
    I'd add this answer to the duplicate. The accepted one there is just plain wrong – juanpa.arrivillaga May 01 '19 at 17:44
  • 1
    It's not so much that `os.putenv` is broken, but that there is an asymmetry between `os.getenv` and `os.putenv`; the former operates on a "mirror" of the environment, and `os.putenv` does not. Using `os.environ` ensures that both the "real" environment and the mirror get updated. – chepner May 01 '19 at 17:52
  • 1
    @chepner: That wouldn't bother me so much if they'd actually given us a way to look past `os.environ` to the real environment variables, but `os.getenv` still looks at the mirror. It might be more accurate to call `os.environ` and `os.getenv` broken, or to call Python's whole environment variable access system broken; it's a matter of perspective. – user2357112 May 01 '19 at 17:56