How to use virtualenv to manage dependencies on a Python application?

Asked

Viewed 1,187 times

24

I need to manage the dependencies of an application Python that I am developing, so that it is easy for other team developers to work on the project using the same versions of the packages that I am using.

I can do that with the virtualenv? Like?

  • @downvoter: care to comment?

  • I did not vote against, but perhaps it is because the issue is a bit wide.

  • Hmmm... Will it be? Broad in what sense? I thought that "How to use virtualenv to manage dependencies" would be specific enough. Anyway, I edited the question trying to clarify. Have any suggestions to improve it?

1 answer

24


[virtualenv][1] builds a "virtual" Python environment, storing all the dependencies in a directory.

Personally, I like to use [virtualenvwrapper][2], which is a set of scripts that make it a little easier to mechanically create these environments.

The steps to build a virtual environment on Ubuntu with virtualenvwrapper are:

  1. Install the virtualenvwrapper:

    sudo pip install virtualenvwrapper

    echo source /usr/local/bin/virtualenvwrapper.sh >> ~/.bashrc

  2. Create a directory where your virtual environments will be:

    mkdir ~/.virtualenvs

  3. Configure the WORKON_HOME virtualenvwrapper environment variable on ~/.bashrc:

    echo 'export WORKON_HOME=$HOME/.virtualenvs' >> ~/.bashrc && . ~/.bashrc

  4. Virtualenvwrapper configuration is ready. Create a new virtual environment with an easy to type name:

    mkvirtualenv web

  5. This command will create an environment with the name web and activate it, indicating the environment name at the shell prompt -- will look something like (web) [user@host] $. You can exit the environment at any time using the command deactivate and work on it again with the command workon web.

Within the environment, you can install the necessary dependencies using the pip, that will install only within the environment, example for an application [Flask][3]:

pip install flask

Once installed, you can create a file with the list of dependencies using:

pip freeze -l > requirements.txt

This will generate a Requirements.txt file with a content similar to:

Flask==0.10.1
Jinja2==2.7.1
MarkupSafe==0.18
Werkzeug==0.9.4
itsdangerous==0.23

And this is it! Now, when another developer wants to make sure to be using the same dependencies as you, he needs to create a virtualenv as well, and install the dependencies from that same file, using the command:

pip install -r requirements.txt

Read more:

http://pythonhelp.wordpress.com/2012/10/17/virtualenv-ambientes-virtuais-para-desenvolvimento/ [1]: http://www.virtualenv.org [2]: http://virtualenvwrapper.readthedocs.org [3]: http://flask.pocoo.org

Browser other questions tagged

You are not signed in. Login or sign up in order to post.