Last active
February 12, 2019 20:01
-
-
Save devhero/7e015f0ce0abacab3880d33c26f07674 to your computer and use it in GitHub Desktop.
A Python context manager for setting/unsetting environment variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.