def preserve_environ(): old = environ.copy() yield # don't touch existing values as os.environ is broken for empty # keys on Windows: http://bugs.python.org/issue20658 for key, value in list(environ.items()): if key not in old: del environ[key] for key, value in old.items(): if key not in environ or environ[key] != value: environ[key] = value