Creating Virtual Environments
Using virtual environments, you can isolate your Python project's dependencies from your global Python environment. This means that each project can maintain its own dependencies, and the default installation does not have any influence. This way you can use different versions of libraries in your project without worrying about how it will break other projects in your system as your virtual environment is a sandbox in which only the current project runs.
At its core, a virtual environment is a directory that contains a project-specific Python interpreter and its associated libraries.
Creating a Virtual Environment
python3 -m venv myenv
The -m flag tells the Python interpreter to run the venv module to create a virtual environment named myenv
When the above command is executed, you see a new directory called myenv. You can see all the files/folders inside myenv folder by running the below command:
ls -lrt myenv/*

Activating the virtual environment
** On macOS and Linux**
Once the virtual environment is created, you can activate your project to use this environment by using the below command:
source myenv/bin/activate
** On Windows **
On Windows OS, you have to run the below command
myenv\Scripts\activate
PATH Variable
Check the PATH variable values before and after activating the virtual environment by running the below command
echo $PATH
Notice how, after activation, the PATH variable is updated to point to the virtual environment's bin directory. This ensures that when you run python, you get the environment-specific interpreter.
Deactivating the virtual environment
You can deactivate your virtual environment by running the below command inside the virtual environment project folder:
deactivate
To Download Modules Via requirements.txt
All the modules necessary for running a specific project are typically listed in a file called 'requirements.txt'
You can download all the required modules by running the below command
pip install -r requirements.txt
Note: You can name this file with any other name. But requirements.txt is the norm.
To auto-generate a requirements.txt file
If you downloaded a set of libraries one at a time through pip, and then want to generate a requirements.txt file automatically based on the packages installed in your environment, you can run the below command:
pip freeze > requirements.txt
Using Virtual Environment for Jupyter Lab
After activating your virtual environment run the below two commands:
pip install ipykernel
This command installs ipykernel, which allows Jupyter to work with this virtual environment.
ipython kernel install --user --name=myenvkernel
This command registers the virtual environment as a new Jupyter kernel with the specified name (myenvkernel).
Now you can start your Jupyter Lab using the command below
jupyter lab
Once the browser opens up, select the new virtual environment that should be used to run the notebook as shown in the screenshot below:


