Os.environ with non-existent keys / environment variables

For a python program, I use os.environ()to get environment variables with a specific key. However, I would like to do something if the key does not exist in the environment, but does not throw KeyError.

I looked through several solutions, but os.environ.get()also os.getenv()seem to act differently than I expect. Is there a way to use os.environ()and still work with non-existent environment variables?

+4
source share
1 answer
os.environ.get("foo")

returns Noneif "foo" is not found.

You can also use

if "foo" in os.environ:
+5
source

All Articles