Sunday 17 January 2016

Python Virtual Environments

In python projects we use different packages of varying versions. Virtual environments help to isolate the dependencies. We can activate a specific environment for a project so as to ensure that it seamlessly works with the respective dependency versions & doesn't interfere with other project which may be using different version of a same package.

To start -
$ apt-get install python-pip
$ pip install virtualenv

If you do a $ pip list here, it will show all the globally installed packages and their versions.
We will store all the environments in a common directory named Environments.
$ mkdir Environments
$ cd !$

Now let's create virtual environment named project_1,
$ virtualenv project_1
Activate the virtual environment project_1,
$ source project_1/bin/activate

The prompt will change a show (project_1) as it is the activated environment. Doing a $ pip list will show only few packages present inside the environment. You can install specific packages required by project inside the environment. E.g.
$ pip install django
To export the packages and version numbers,
$ pip freeze --local > requirements.txt

To get out of the virtual environment,
$ deactivate

To get rid of the virtual environment just delete its directory.
$ rm -rf project_1/

To create environment with specific python version,
$ virtualenv -p /usr/bin/python2.7 py27_env

To install all the packages in this virtual environment,
$ pip install -r requirements.txt

This completely touches on basics of virtual environments in python.

No comments:

Post a Comment

Your comments are very much valuable for us. Thanks for giving your precious time.

Do you like this article?