Python Virtual Environments
Sometimes, one Python environment may not be enough. For instance, you may find yourself working on multiple Django projects at once – each with different Python package requirements. I personally ran into this problem when writing a feature which required the bleeding-edge version of Django. Repeatedly installing/uninstalling different Django versions is redundant, and virtual environments are the answer.
To get started, install virtualenv and virtualenvwrapper:
pip install virtualenv
pip install virtualenvwrapper
Add the following to ~/.bashrc:
# virtualenvwrapper
export WORKON_HOME=~/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh
export PIP_VIRTUALENV_BASE=$WORKON_HOME
export PIP_RESPECT_VIRTUALENV=true
Lastly, create the virtual environment directory and execute ~/.bashrc:
mkdir ~/.virtualenvs
source ~/.bashrc
Now you can create isolated Python environments using mkvirtualenv envname. I have one called “rb”, and one called “rbalpha” which contain different Python packages. After an environment is activated, you’ll see (envname) next to your username in bash. You can activate an environment by simply using workon envname.
Once you are in your environment, Python packages can be installed in a similar manner as before. The only difference is you don’t use sudo when installing packages with pip or setup.py install. If you do this, the packages will be installed to the system’s Python environment.
Pro tip: To list the current environment’s Python packages, use pip freeze.
Recent Comments