Sunday, December 20, 2015

Python Virtualenv on OSX

Install virtualenv

Johns-MBP:~ johnroberts$ pip install virtualenv

Johns-MBP:~ johnroberts$ mkdir -p ~/Virtualenvs

Johns-MBP:~ johnroberts$ mkdir -p ~/Projects

Johns-MBP:~ johnroberts$ cd ~/Virtualenvs/

Create the virtual environments

Johns-MBP:~ johnroberts$ virtualenv foobar
New python executable in foobar/bin/python2.7
Also creating executable in foobar/bin/python

Installing setuptools, pip, wheel...done.

Johns-MBP:~ johnroberts$ virtualenv -p python3 foobar-py3
Running virtualenv with interpreter /usr/local/bin/python3
Using base prefix '/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5'
New python executable in foobar-py3/bin/python3.5
Also creating executable in foobar-py3/bin/python

Installing setuptools, pip, wheel...done.

This should get Virtualenv in place.

Activate an environment

We made the Python environment, now we need to activate it.

Johns-MBP:~ johnroberts$ source foobar/bin/activate
(foobar)Johns-MBP:~ johnroberts$ 

Notice the "(foobar)" which shows that we are now in the environment.

What version of python are we using

We can check which version of python
(foobar)Johns-MBP:~ johnroberts$ which python

This shows that we are using python from our environment.

(foobar)Johns-MBP:~ johnroberts$ python --version
Python 2.7.10

We can also check pip
(foobar)Johns-MBP:~ johnroberts$ which pip

Use pip to see what packages are here

(foobar)Johns-MBP:~ johnroberts$ pip list
pip (7.1.2)
setuptools (18.2)

wheel (0.24.0)

If I did pip list outside of this environment I'd get a lot of packages (I won't list them here)

Install the packages for this environment
(foobar)Johns-MBP:~ johnroberts$ pip install numpy
Collecting numpy
  Downloading numpy-1.10.2-cp27-none-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (3.7MB)
    100% |████████████████████████████████| 3.7MB 143kB/s 
Installing collected packages: numpy
Successfully installed numpy-1.10.2

Cool as a cucumber.

List of Dependencies

Make a list of dependencies for this project and view it using cat
(foobar)Johns-MBP:~ johnroberts$ pip freeze --local > requirements.txt
(foobar)Johns-MBP:~ johnroberts$ cat requirements.txt 

The list of dependencies is very useful for recreating other environments using pip. Create the environment and then use pip and the requirements.txt file to install the dependencies.

    pip install -r requirements.txt

Get out of the environment - deactivate

We just type deactivate
(foobar)Johns-MBP:~ johnroberts$ deactivate
Johns-MBP:~ johnroberts$ 

Notice that "(foobar)" has been removed. We are no longer in that environment.

Remove the Virtual Environment
Once deactivated, we can remove:
Johns-MBP:~ johnroberts$ rm -rf foobar/


No comments:

Post a Comment