Python | Setting up virtual env

Virtual Environments

Python applications will often use packages and modules that don’t come as part of the standard library. Applications will sometimes need a specific version of a library, because of various reasons.

This means it may not be possible for one Python installation to meet the requirements of every application.The solution for this problem is to create a virtual environment, a self-contained directory tree that contains a Python installation for a particular version of Python, plus a number of additional packages.

Creating Virtual Environments

The module used to create and manage virtual environments is called venv. Open the terminal and write below command.

   
python -m venv gcptutorials-env
   

virtual-environments

This will create the gcptutorials-env directory if it doesn’t exist, and also create directories inside it containing a copy of the Python interpreter and various supporting files.

Activating Virtual Environments

Write below command to activate virtual environment on Windows.

   
.\gcptutorials-env\Scripts\activate
   

virtual-environments

Once the virtual environment is activated you should virtual environment name in the prompt.

Install package to Virtual Environment

Now we have virtual environment activated lets install a Python package inside the virtual environment. This package will be available only in this env and not in our base installation. We will verify that in next section.

   
pip install arrow
 

virtual-environments

   
pip show arrow
 

virtual-environments

We installed arrow module using pip and checked its version using pip show arrow command. Now let's deactivate the environment.

Deactivating Virtual Environment

Write below command to deactivate virtual environment on Windows.

   
deactivate
   

Now we are out of virtual environment, let's validate that arrow module is not available in base environment.

   
pip show arrow
   

virtual-environments