# Python - How To Specify Virtual Environment for a Python Version

ID : 441

viewed : 105

92

This article will explain how to specify or create a new virtual environment for some specific Python version. A virtual environment is an isolated Python environment with Python libraries, interpreters, and scripts installed and isolated from the system Python environment.

A virtual environment is useful to provide the dependencies required for a specific Python project separately. We can specify the separate virtual environment by using the following methods.

## Specify Virtual Environment for a Python Version Using the virtualenv Command

We can create Python virtual environment by using the virtualenv command for a specific Python version.

The virtualenv command modifies the environment variables in a shell to create an isolated Python virtual environment. Therefore, we must install the shell to execute the virtualenv command.

We can create Python virtual environment for a specific Python version using the shell by executing the following command:

virtualenv -p=/usr/bin/python<version> path/to/new/virtualenv/ 

If the virtualenv package is not installed on the computer, we can install it first using the following command:

pip install virtualenv 

## Specify Virtual Environment Using the venv Command

We can create Python virtual environment by using the venv command. The venv command first creates the targeted directory if it does not exist and then adds the pyvenv.cfg file in it.

The commonly used name for the target directory is .venv. It creates a bin or Scripts (for Windows) subdirectory containing Python binaries and a site-packages subdirectory within the target directory.

The venv command, unlike virtualenv, does not permit creating a virtual environment for some specific Python version. We can create Python virtual environment by executing the following command.

python3 -m venv path/to/new/virtualenv/ 

In Linux and macOS, we can activate the virtual environment by using the following command:

source <path/to/new/virtualenv>/bin/source 

You can use the following command in cmd.exe to activate the virtual environment if you are using Windows.

<path\to\new\virtualenv>\Scripts\activate.bat 

After a virtual environment is active, the VIRTUAL_ENV variable is set to the specified path of the virtual environment. And Python starts using the virtual environment’s interpreter, libraries, and scripts.