How to create a virtual environment for Python


First, we need to install virtualenv using pip, which will help us create a standalone virtual environment where we can specify the version of Python. It is also possible to install specific versions of third-party libraries.

pip install virtualenv

Creating a virtual environment with virtualenv

Before using the virtualenv command to create a virtual environment, we need to enter a specified directory, because virtualenv will create various configuration files for this virtual environment in the current path.

cd ~/python # Choose your path
virtualenv my_env_name

"my_env_name" will be the name of the virtual environment we create (the name is up to you). Since we are in the ~/python directory, virtualenv will create a directory named "my_env_name" in this path, which will generate a set of files needed for the virtual environment.

Activate/Deactivate the virtual environment

.\my_env_name\Scripts\activate # On Windows
source my_env_name/bin/activate # On Mac or Linux

With the virtual environment active, type deactivate

When using a virtual environment, you'll need to install all required packages inside the virtual environment. Virtual environments are isolated from each other and from the system's default Python environment.