Python (Scripting) - Setting environment variables in a virtual environment (venv virtualenv)

by
Jeremy Canfield |
Updated: March 23 2023
| Python (Scripting) articles
Let's say there are certain environment variables that you want set every time you activate a Python virtual environment.
Of course, you could manually create the environment variables using export.
export FOO=Hello
export BAR=World
However, this is kind of a pain having to do this each time you activate the virtual environment. One easy option here is to add the export commands at the bottom of the /bin/activate file, so that the environment variables are created after the virtual environment has been activated.
You would also want to unset FOO and unset BAR at the end of the deactivate function in the /bin/activate file.
deactivate () {
# reset old environment variables
if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then
PATH="${_OLD_VIRTUAL_PATH:-}"
export PATH
unset _OLD_VIRTUAL_PATH
fi
if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then
PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}"
export PYTHONHOME
unset _OLD_VIRTUAL_PYTHONHOME
fi
# This should detect bash and zsh, which have a hash command that must
# be called to get it to forget past commands. Without forgetting
# past commands the $PATH changes we made may not be respected
if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
hash -r
fi
if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
PS1="${_OLD_VIRTUAL_PS1:-}"
export PS1
unset _OLD_VIRTUAL_PS1
fi
unset VIRTUAL_ENV
if [ ! "$1" = "nondestructive" ] ; then
# Self destruct!
unset -f deactivate
fi
unset FOO
unset BAR
}
Did you find this article helpful?
If so, consider buying me a coffee over at