Virtual Environment for Python based application

Python virtual environment: Here, we are going to learn what is python virtual environment, why do we need a virtual environment, and how to create a virtual environment in Python3? By Sapna Deraje Radhakrishna Last updated : December 16, 2023

What is Virtual Environment in Python?

Virtual environments are very useful when the application requires a separate environment, each using its version of python and libraries for execution. Similar to virtual environment, there are packaging tools like "Anaconda" and "Miniconda".

The virtual environment is the easiest and recommended way to configure a custom python environment.

Why do we need a virtual environment?

The virtual environment is a clever way to keep the python setup isolated with other projects. As a user, one can have multiple virtual environments in a single machine and each virtual environment can have different libraries as per the requirements. We can also package a virtual environment like a zip file with all dependencies needed for the application and deploy it on serverless service like AWS lambda.

How to create a virtual environment using Python3?

Step 1: Install virtual environment

Below are the commands to Install Virtual Environment:

pip3 install virtualenv
Collecting virtualenv
  Downloading virtualenv-15.1.0-py2.py3-none-any.whl (1.8MB)
    100% |████████████████████████████████| 1.8MB 367kB/s
Installing collected packages: virtualenv
Successfully installed virtualenv-15.1.0

Step 2: Create the virtual environment

Using python3, the command to create the virtual environment and the syntax is 'python3 –m venv /path/to/create/the/virtual/env'.

-bash-4.2$ python3 -m venv test_venv
-bash-4.2$ ls

Step 3: Activate virtual environment

Below is the command to activate virtual environment:

-bash-4.2$ source test_venv/bin/activate
(test_venv) -bash-4.2$

Step 4: Install the required libraries

Install the required libraries, using pip (for the example below, we have used 'flask' library)

(test_venv) -bash-4.2$ pip3 install flask
Collecting flask
  Downloading (94kB)
    100% |████████████████████████████████| 102kB 3.8MB/s
Collecting Jinja2>=2.10.1 (from flask)
  Using cached
Collecting click>=5.1 (from flask)
  Using cached
Collecting itsdangerous>=0.24 (from flask)
  Using cached
Collecting Werkzeug>=0.15 (from flask)
  Using cached
Collecting MarkupSafe>=0.23 (from Jinja2>=2.10.1->flask)
  Using cached
Installing collected packages: MarkupSafe, Jinja2, click, itsdangerous, Werkzeug, flask
Successfully installed Jinja2-2.10.1 MarkupSafe-1.1.1 Werkzeug-0.16.0 click-7.0 flask-1.1.1 itsdangerous-1.1.0
 (test_venv) -bash-4.2$

Python Tutorial

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.