Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@hngkr
Created July 12, 2019 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hngkr/8bb63bed26b2047c8dbfb75d554e0add to your computer and use it in GitHub Desktop.
Save hngkr/8bb63bed26b2047c8dbfb75d554e0add to your computer and use it in GitHub Desktop.
setenviron contextmanager source code
import contextlib
import os
@contextlib.contextmanager
def setenviron(envdict=None, **mapping):
"""``with`` context to temporarily modify the environment variables"""
_environ = os.environ.copy()
if envdict:
for key, value in envdict.items():
os.environ[key] = str(value)
for key, value in mapping.items():
os.environ[key] = str(value)
try:
yield
finally:
os.environ.clear()
os.environ.update(_environ)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment