Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

os.environ with nonexistent keys/environment variables

For a python program, I am using os.environ() to get environment variables with a certain key. However, I would like to be able do something if the key is nonexistent in the environment, instead of throwing a KeyError.

I've looked up a few solutions, but os.environ.get() and os.getenv() seem to act differently than how I expect. Is there any way to use os.environ() and still work around nonexistent environment variables?

like image 438
user3562406 Avatar asked Nov 05 '14 06:11

user3562406


1 Answers

os.environ.get("foo")

returns None if "foo" is not found.

You can also use

if "foo" in os.environ:
like image 54
John La Rooy Avatar answered Nov 05 '22 06:11

John La Rooy