100 Useful Command-Line Utilities

by Oliver; 2014

101. virtualenv

Note: virtualenv is not a default shell program. You have to download and install it.

Do you use Python? virtualenv is a special command line tool for Python users. We learned about package managers in An Introduction to the Command-Line (on Unix-like systems) - Installing Programs on the Command Line, and Python's is called pip. Suppose you're working on a number of Python projects. One project has a number of dependencies and you've used pip to install them. Another project has a different set of dependencies, and so on. You could install all of your Python modules in your global copy of Python, but that could get messy. It would be nice if you could associate your dependencies with your particular project. This would also ensure that if two projects have conflicting dependencies—say they depend on different versions of the same module—you can get away with it. Moreover, it would allow you to freely install or update modules to your global Python worry-free, since this won't interfere with your projects. This is what virtualenv does and why it's a boon to Python users.

Following the docs, first install it:
$ sudo pip install virtualenv
To make a new Python installation in a folder called venv, run:
$ virtualenv venv
To emphasize the point, this is a whole new copy of Python. To use this Python, type:
$ source venv/bin/activate
As a sanity check, examine which Python you're using:
(venv) $ which python
/some/path/venv/bin/python
It's virtualenv's copy! Now if you, say, install Django:
(venv) $ pip install Django
You can see that you only have the Django module (and wheel):
(venv) $ pip freeze
Django==1.8.7
wheel==0.24.0
Django's source code is going to be installed in a path such as:
venv/lib/python2.7/site-packages
In practice, if you were doing a Django project, everytime you wanted to start coding, the first order of business would be to turn on virtualenv and the last would be to turn it off. To exit virtualenv, type:
(venv) $ deactivate

<PREV   NEXT>