Skip to content

Instantly share code, notes, and snippets.

@devhero
Last active February 12, 2019 20:01
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devhero/7e015f0ce0abacab3880d33c26f07674 to your computer and use it in GitHub Desktop.
Save devhero/7e015f0ce0abacab3880d33c26f07674 to your computer and use it in GitHub Desktop.
A Python context manager for setting/unsetting environment variables
"""
Context manager for environment variables
Usage:
os.environ['MYVAR'] = 'oldvalue'
with EnvironmentContex(MYVAR='myvalue', MYVAR2='myvalue2'):
print os.getenv('MYVAR') # Should print myvalue.
print os.getenv('MYVAR2') # Should print myvalue2.
print os.getenv('MYVAR') # Should print oldvalue.
print os.getenv('MYVAR2') # Should print None.
"""
import os
class EnvironmentContext(object):
def __init__(self, **kwargs):
self.envs = kwargs
def __enter__(self):
self.old_envs = {}
for k, v in self.envs.items():
self.old_envs[k] = os.environ.get(k)
os.environ[k] = v
def __exit__(self, *args):
for k, v in self.old_envs.items():
if v:
os.environ[k] = v
else:
del os.environ[k]
@sakurai-youhei
Copy link

Do you have plan to publish this to PyPI? I wish the envcontext was available via pip under MIT license. :) If you don't have plan but agree with the licensing at least, I'll probably do it with adding chain of authors whom I found: @devhero (you), @sidprak (upstream) and @igniteflow (root). Thanks.

@sakurai-youhei
Copy link

FYI: I've published envcontext at PyPI finally.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment