Managing Python virtual environments on Mac using pyenv and virtualenvwrapper
Step 1. Setup pyenv-virtualenv
Make sure that your Mac has brew
installed. If not, run the following code to install brew:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
If the above code does not work, go to the Homebrew page to check installation details.
brew install pyenv-virtualenv
Step 2. Download python versions
As an example, we can download target Python 3.4.4 version using pyenv by entering pyenv install 3.4.4
, or Python 2.7 by entering pyenv install 2.7
Step 3: Setup virtualenvwrapper
Install pip
Make sure that you have pip
installed in your computer. If you don’t have it yet, install by running sudo easy_install pip
on your terminal
Install virtualenvwrapper
Then run sudo pip install virtualenvwrapper
. Once virtualenvwrapper is installed, look for the the directory of virtualenvwrapper.sh
by entering which virtualenvwrapper.sh
. Once this is done, this should output something like /usr/local/bin/virtualenvwrapper.sh
Create virtual environment directory
Create a permanent directory for all virtual environments that will created using virtualenvwrapper
by entering mkdir ~/.virtualenvs
Setup environment variables
Create/edit your ~/.bash_profile
or ~/.bash_rc
to contain the following:
# directory for virtualenvs created using virtualenvwrapper
export WORKON_HOME=/Users/vivi/.virtualenvs# ensure all new environments are isolated from the site-packages directory
export VIRTUALENVWRAPPER_VIRTUALENV_ARGS='--no-site-packages'# use the same directory for virtualenvs as virtualenvwrapper
export PIP_VIRTUALENV_BASE=$WORKON_HOME# makes pip detect an active virtualenv and install to it
export PIP_RESPECT_VIRTUALENV=true
if [[ -r /usr/local/bin/virtualenvwrapper.sh ]]; then
source /usr/local/bin/virtualenvwrapper.sh
else
echo "WARNING: Can't find virtualenvwrapper.sh"
fi
Enter source ~/.bash_profile
or source ~/.bash_rc
for the above code to take effect
Step 4. Usage of pyenv virtualenvs and virtualenvwrapper
Setup global python version
Setup a global (pyenv) python version (for example, Python 3.4.4) by entering pyenv global 3.4.4
. To check if this is successful, run pyenv which python
and this should output something like /Users/vivi/.pyenv/versions/3.4.4/bin/python
Create virtualenv using virtualenvwrapper
mkvirtualenv --python=`pyenv which python` models
List existing virtualenvs
lsvirtualenv
Delete virtualenv
rmvirtualenv
Activate (or switch to) virtualenv
workon virtualenv
Deactivate virtualenv
deactivate virtualenv