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

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter 4b3d29 in the box below so that we can be sure you are a human.