TroyGrosfield.com TroyGrosfield.com

Headline

Making the Move to Python 3: Python3, Virtual Environments and pip

Author
by Troy Grosfield
Date
January 9th, 2014
Category
Developer
Story

I finally made the move to converting all my apps to python 3 and it wasn’t nearly as painful as I was expecting.  One main hurdle was to figure out how to correctly get a virtual environment created with python 3 using the correct version of pip.

My initial attempt to create a virtual environment (venv) was successful, but when I would activate my virtual environment it was still installing pip installed apps to my system python instead of in the virtual environment.  Let’s get started…

Create the Virtual Environment

Creating virtual environments in python 3 is extremely simple [1]:

$ python3 -m venv /path/to/venv/myenv

Activate the Virtual Environment

After the venv was created, you need to activate it:

$ source /path/to/venv/myenv/bin/activate

Installing the Correct pip in Virtual Environment

Here’s where it threw a curve ball on me.  When I went to pip install my apps in my virtual environment, I realized it wasn’t using the correct version of pip.

(myenv) $ which pip
/usr/local/bin/pip
(myenv) $ pip --version
pip 1.5 from /Library/Python/2.7/site-packages/pip-1.5-py2.7.egg (python 2.7)

So, I went ahead and followed the steps in pip-installer.org’s site [2].

Install setuptools in Virtual Environment

wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py 
python ez_setup.py 
rm ./ez_setup.py 
rm ./setuptools-*.tar.gz

Install pip in Virtual Environment

wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py 
python get-pip.py 
rm ./get-pip.py

Reactive your Virtual Environment

In order for the changes to take affect, you will need to reactivate your virtual environment.

(myenv) $ myenv source /path/to/venv/myenv/bin/activate
(myenv) $ myenv which pip
/path/to/venv/myenv/bin/pip
(myenv) $ myenv pip --version
pip 1.5 from /path/to/venv/myenv/lib/python3.3/site-packages (python 3.3)

Now when you pip install your apps they will go into the correct directory in your virtual environment:

/path/to/venv/myenv/lib/python3.3/site-packages

Hope this helps!

References

Tags
Comments
No Comments »

No Comments Yet

Leave a reply