Skip to content

Instantly share code, notes, and snippets.

@nikhilgeo
Last active October 29, 2020 14:47
Show Gist options
  • Save nikhilgeo/736b21b927fe5cfa76a79cda530c19ce to your computer and use it in GitHub Desktop.
Save nikhilgeo/736b21b927fe5cfa76a79cda530c19ce to your computer and use it in GitHub Desktop.
Working with python2 and python3 on macOS, Windows and Ubuntu

In macOS Catalina

python2 and python3 is already installed and python command on terminal points to python2

➜  ~ python --version
Python 2.7.16
➜  ~ python3 --version
Python 3.7.3

# Install virtualenv and virtualenvwrapper
sudo pip3 install virtualenv
sudo pip3 install virtualenvwrapper

# Set PATH. Ref: https://virtualenvwrapper.readthedocs.io/en/latest/install.html#python-interpreter-virtualenv-and-path
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 <- which python3
export VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin/virtualenv
source /usr/local/bin/virtualenvwrapper.sh

# Create folder for virtual env
cd ~
virtualenv .venv
export WORKON_HOME=$HOME/.venv

# Create virtual env for python2 and python3
mkvirtualenv -p python2 python2
mkvirtualenv -p python3 python3

# Use python2 virtual env
➜  ~ workon python3
(python3) ➜  ~ python --version
Python 3.7.3
(python3) ➜  ~ deactivate
➜  ~ python --version
Python 2.7.16
➜  ~ python3 --version
Python 3.7.3

Open the file .zshrc (vim ~/.zshrc) and add below line to the top.

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

In Ubuntu 18.04

Default python is python2 install python3 by apt-get install python3. Now create virtual environment to work on python2 and python3 with-out issues.

$ python
Python 2.7.15rc1 (default, Nov 12 2018, 14:31:15)
>>>
#Install virtual environment for python2
pip install virtualenv

#Create virtual environment venv-2 for python2
python -m virtualenv venv-2

#Install virtual environment for python3
apt-get install python3-venv

#Create virtual environment venv-3 for python3
python3 -m venv venv-3

#Start venv-2
source venv-2/bin/activate
#Start venv-3
source venv-3/bin/activate

In Windows 10

Download the python2 and install it. Remember to check the option add to PATH Download the python3 and install it. DO NOT check the option add to PATH Now create virtual environment for python2 and python3

#Install the virtual environments
py -2 -m virtualenv venv-2
py -3 -m venv venv-3

#Start the virtual environment
venv-2\Scripts\activate
venv-3\Scripts\activate

#Stop the virtual environment
deactivate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment