Skip to content

Virtual Environment

  • Now, let us discuss about the virtual environment.

  • Virtual environment is a tool using which we can manage our project dependencies.

  • It creates an isolated python environment where you can install the libraries and modules required by your project.

  • In this virtual environment, all the packages, modules and libraries are isolated from your global python environment.

  • Let's take an example, suppose you have installed the latest version of Django in your global python environment, and if want to work on some older version of Django, then simply you will create a virtual environment and install the older version of Django without affecting the libraries and modules installed in global python environment.

  • Now, let us learn how to create, activate and deactivate virtual environment in our system.

Creating a Virtual Environment

  • First of all, open the visual studio code and open the directory where we initialized our git repository.

  • Now, open the terminal of your VS code.

  • After that, to create a virtual environment, we need to execute this command.

    python -m venv env
    
  • Here, We are creating a virtual environment using the venv library which is by default installed when you install python in your system and env is the name of our virtual environment.

Activating the virtual environment

  • After creating the virtual environment, we need to explicitly activate our virtual environment before we install any libraries and modules.

  • The code for windows and Linux based operating systems are different

  • To activate the virtual environment in the windows operating system, type here

    env\Scripts\activate
    

    NOTE: Make sure you use backward slash instead of forward slash

  • To activate the virtual environment in Linux based operating system, type here

    source env/bin/activate
    

    NOTE: Make sure you use forward slash instead of backward slash

Deactivating the virtual environment

  • Now, to deactivate the virtual environment, the process is very easy. Just type

    deactivate
    
  • This code works both in windows and Linux based os.