Python Virtual Environment

Posted by Meenakshy on Sept. 25, 2021, 5:22 p.m.

What really is a virtual environment? This article will be a beginner’s guide to virtual environments and dependency managers in Python. We will discuss how to create and manage different virtual environments for your python projects each using different python versions and libraries for execution.

What is a virtual environment?

The core idea behind virtual environments is to create an isolated environment for your projects. Each project has its own dependencies, which may be conflicting with the dependencies of others. 

If you want to install a library for your Python project and install it using

pip install <library_name>

without  a virtual environment, all libraries will be installed globally, which is not a good practice, if multiple projects work on your system.

A virtualenv is simply a directory with a particular structure. It has a bin subdirectory that includes links to a Python interpreter as well as subdirectories that hold packages installed in the virtualenv. By invoking the Python interpreter using the path to the virtualenv's bin subdirectory, the interpreter only uses the packages installed within the virtual environment.

The packages installed in each virtual environment are seen only in that environment and no other. Creating different virtual environments for your projects, helps in managing projects with different dependencies. There are no limits to the number of environments you can create.

Why do we need a Virtual environment?

  • You can use any version of python you want for a specific environment without having to worry about collisions
  • One machine can handle many projects in different environments.
  • Helps in managing libraries for a project.

Installation:

Since venv comes pre-installed in Python3 and newer, there is no need to install it.

For older python version install virtual environment using:

pip install virtualenv

Creating virtual environment:

Virtual environment can be created by the following command.

python3 -m venv <virtual env name>

or 

virtualenv <virtual env name> -p python_version

Activation:

Before using the virtual environment, we need to activate it. This makes the current virtual environment you’re working on to temporarily function as the default Python interpreter.

source <virtual env name>/bin/activate

Deactivation:

After done with your environment you can deactivate it by using:

deactivate

If your working with a team it is better to create a file called requirements.txt, which contains all the dependencies for the project

we can create the requrements.txt using the command

pip freeze > requirements.txt

Keep this file as part of your projects. We can install all the dependencies using the command

pip install -r requirements.txt