virtualenvwrapper (Part 2)
Here I describe how I use virtualenvwrapper.
I keep my virtual environments in the default location (
~/.virtualenvs folder). My Python projects are kept in Dropbox. If a project (call it “
stuff” for instance) has a virtual env., then I add the suffix “
_project” to the projects’s folder name (resulting “
stuff_project” in this example). This way I can see it immediately (without entering the folder) that it has an attached venv.
stuff_project folder create a
requirements.txt file that contains all the modules that you installed in your venv. This way you can re-create your venv on another machine and continue to work on yout project.
Let’s see a concrete example. Say I want to create a new Django project:
$ cd $HOME/Dropbox/python/webapps $ mkdir stuff_project # ^ every project file will be in this folder $ cd stuff_project $ django-admin.py startproject stuff # ^ create the Django project $ mkvirtualenv stuff_project # ^ venv is created AND activated $ pip install django $ pip install django-extensions # ^ useful extensions $ pip freeze --local >requirements.txt # ^ packages installed in the venv are listed in this file
Since I put the project folder in Dropbox, it will be synced on all my machines. What to do if I want to work on this project on another machine of mine (let’s call it “machine #2”)? The virtual environment will be missing. But there is no need to worry. We have a
requirements.txt file and from this we can populate a newly created venv. Install virtualenvwrapper on machine #2 and create an empty venv for the project:
# actions to perform on machine #2: $ cd $HOME/Dropbox/python/webapps/stuff_project $ mkvirtualenv stuff_project # ^ the venv is created and activated $ pip install -r requirements.txt # ^ packages are installed in the venv
When you are done with the project, deactivate the venv with the “deactivate” command. Since it’s too long, I put an alias on it:
If you install new packages in the venv, don’t forget to update the
requirements.txt file (
pip freeze >requirements.txt )!