A context manager that updates os.environ.
(updates)
| 162 | |
| 163 | @contextlib.contextmanager |
| 164 | def env_modify(updates): |
| 165 | """A context manager that updates os.environ.""" |
| 166 | # This could also be done with mock.patch.dict() but taking a dependency |
| 167 | # on the mock library is probably not worth the benefit. |
| 168 | old_env = os.environ.copy() |
| 169 | print("env_modify: " + str(updates)) |
| 170 | # Setting a value to None means clear the environment variable |
| 171 | clears = [key for key, value in updates.items() if value is None] |
| 172 | updates = {key: value for key, value in updates.items() if value is not None} |
| 173 | os.environ.update(updates) |
| 174 | for key in clears: |
| 175 | if key in os.environ: |
| 176 | del os.environ[key] |
| 177 | try: |
| 178 | yield |
| 179 | finally: |
| 180 | os.environ.clear() |
| 181 | os.environ.update(old_env) |
| 182 | |
| 183 | |
| 184 | def ensure_dir(dirname): |