Skip to content

Instantly share code, notes, and snippets.

@zetc0de
Forked from recto/PythonVirtualenvMac.md
Created August 28, 2020 02:41
Show Gist options
  • Save zetc0de/2e1f392496bc6d94b86fcbb3c6316794 to your computer and use it in GitHub Desktop.
Save zetc0de/2e1f392496bc6d94b86fcbb3c6316794 to your computer and use it in GitHub Desktop.
Python 2 and 3 setup with virtualenv on Mac OS X

Python Installation

You can install the latest python 2 and python 3 by homebrew.

  • Python 2 Installation
brew install python
  • Python 3 Installation
brew install python3

virtualenv Installation

virtualenv is a tool to create isolated Python environments. virtualenv creates a folder, which contains all the necessary executables to use the packages that a Python project would need.

You can install virtualenv with pip.

pip install virtualenv

virtualenvwrapper is a set of extensions to virtualenv tool. The extensions include wrappers for creating and deleting virtual environments and otherwise managing your development workflow, making it easier to work on more than one project at a time without introducing conflicts in their dependencies. You can install virtualenvwrapper with pip.

pip install virtualenvwrapper

Creating Virtual Environment

Set environment variables for virtualenv.

export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python
export VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin/virtualenv

Source virtualenvwrapper.sh.

source /usr/local/bin/virtualenvwrapper.sh

Create a virtual env directory, which contains all the necessary executables to use the packages that a Python project would need.

virtualenv .venv

Set WORKON_HOME for virtualwrapper

export WORKON_HOME=$HOME/.venv

Create a virtual environment for python 2.

mkvirtualenv -p /usr/bin/python python2

Create a virtual environment for python 3.

mkvirtualenv -p /usr/local/bin/python3 python3

Add the following to .bash_profile.

export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python
export VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin/virtualenv
source /usr/local/bin/virtualenvwrapper.sh
export WORKON_HOME=$HOME/.venv

Working on Virtual Environment

Set environment variables if not done yet.

export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python
export VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin/virtualenv
source /usr/local/bin/virtualenvwrapper.sh
export WORKON_HOME=$HOME/.venv

Perform workon command and select the virtual environment.

workon python3

Configure/Install packages under virtual envirnment as needed. Once you are done with your work, you can deactivate the virtual environment and get back to system default environment.

deactivate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment