How To Create Virtual Environment in Python

Virtual Environment in Python lets you work on different python environments for different projects which require different versions of same dependencies. Suppose, you are working in two projects at the same time. The two projects require different versions of Python. You can't work on two projects at the same time on host environment. In such cases, you can create two different virtual environments with different versions of python.

Virtualenv is a tool to create virtual python environments. It allows to create an isolated environment that has its own installation directory and doesn’t share dependencies with other virtual environments.

Lets go through the common commands to create and manage virtual environments using Virtualenv:
 Note: Run following commands on terminal (command prompt).

Intalling Virtualenv:

You can install Virtualenv tool with PIP package manager:
pip install virtualenv

Create Virtual Environment:

Go to the directory where you want to create virtual environment and type the following:
virtualenv virtual_env1
- "virtual_env1" is the name of your virtual environment. It creates a directory on this name.
Instead, you can also use a specific Python interpreter of your choice as a default interpreter for your virtual environment. (e.g. python2.7)
virtualenv -p /usr/bin/python2.7 virtual_env1

Activate Virtual Environment:

Before working on the environment, you need to activate it by typing:
Linux/Mac OS:
source virtual_env1/bin/activate
Windows:
virtual_env1\Scripts\activate
Now you should see the name of virtual environment in brackets on your terminal like: (virtual_env1)

Install Dependencies:

To install packages and dependencies required for your project, you need to first activate the environment. Then, you can install the required dependencies using the PIP command. Even if the package is installed on home environment or another virtual environment, you need to pip install again for this virtual environment.

Deactivate:

If you want to deactivate the virtual environment, type the following:
deactivate

Remove Virtual Environment:

To completely delete the virtual environment along with the installed packages, simply delete the folder of virtual environment.
Linux/Mac OS:
rm -rf directroy/

There are other things you can do with this Virtualenv tool. For more, go to this documentation.

Comments