Context manager to update environment variables with preservation
pip install envcontext
from os import environ, getenv
from envcontext import EnvironmentContext as EnvContext
environ["TEST_VAR1"] = "original"
with EnvContext(TEST_VAR1="updated", TEST_VAR2="added"):
print(environ["TEST_VAR1"]) # Prints "updated".
print(environ["TEST_VAR2"]) # Prints "added".
print(getenv("TEST_VAR1")) # Prints "original".
print(getenv("TEST_VAR2")) # Should print "None".
from subprocess import check_output
from envcontext import EnvironmentContext as EnvContext
with EnvContext(PGPASSWORD="very-secret-password"):
check_output(["psql", "..."]) # psql process can manipulate PGPASSWORD.
Note: Ex. 2 is not working on Python 2.x because subprocess module bundled in Python 2.x doesn't propagate environment variables from current to child process.