How to use virtualenv to manage the dependencies of a Python application?

22

I need to manage the dependencies of a Python application I'm developing, so it's easy for other team developers to be able to work on the project using the same versions of the packages I'm using.

Can I do this with virtualenv ? How?

    
asked by anonymous 11.12.2013 / 17:50

1 answer

23

virtualenv assembles a "virtual" Python environment, storing all dependencies in a directory.

Personally, I like using the virtualenvwrapper , which is a set of scripts that make the mechanics of creating these environments a bit easier.

The steps to set up a virtual environment in Ubuntu with virtualenvwrapper are:

  • Install virtualenvwrapper:

    sudo pip install virtualenvwrapper

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

  • Create a directory where your virtual environments will be:

    mkdir ~/.virtualenvs

  • Set the virtualenvwrapper WORKON_HOME environment variable in ~/.bashrc :

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

  • The virtualenvwrapper configuration is ready. Create a new virtual environment with an easy-to-type name:

    mkvirtualenv web

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

  • Inside the environment, you can install the required dependencies using pip , which will install just inside the environment, example for an application Flask :

    pip install flask
    

    After installation, you can create a file with list of dependencies using:

    pip freeze -l > requirements.txt
    

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

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

    And that's it! Now when another developer wants to make sure that they are using the same dependencies as you, he can create a virtualenv as well, and install the dependencies from that same file, using the command:

    pip install -r requirements.txt
    

    Read more:

    link

        
    11.12.2013 / 17:50