How to Setup a Virtual Environment in Python

A virtual environment is a tool that helps to keep dependencies required by different projects in separate places, by creating virtual Python environments for them. It solves the "Project X depends on version 1.x but, Project Y needs 4.x" dilemma and keeps your global site-packages directory clean and manageable.

Step-by-Step Guide

Step 1: Install virtualenv

If you haven't installed virtualenv yet, you can do so using pip (Globally install this) :

pip install virtualenv

Step 2: Create a Virtual Environment

Create a new directory for your project (if you haven't already), navigate to it, and run:

virtualenv env

This will create a directory named env in your project folder that contains the virtual environment.

Step 3: Activate the Virtual Environment

To start using the virtual environment, you need to activate it. The command differs based on your operating system:

Once activated, your command prompt will change to indicate that you're now working within the virtual environment.

Step 4: Install Packages

Now that the virtual environment is activated, you can install packages using pip. For example:

pip install requests

Step 5: Deactivate the Virtual Environment

When you're done working in the virtual environment, you can deactivate it by simply running:

deactivate

Your command prompt will revert to its usual state, indicating that you are no longer working in the virtual environment.

Additional Tips