Many a time, you might have come across situations where your existing Python interpreter gets loaded & messed up with too many unrelated libraries leading to cumbersome.
To avoid such situations, the Python community always suggests having a separate Virtual Environment for each task/project.
Ways of Creating a Virtual Environment:
1. Virtualenv
2. Pipenv (My favorite)
Usually, Python3 comes with pip preinstalled. If you get an error “pip command not found”, use the following command to install pip:
sudo easy_install pip
A tool for creating isolated virtual
Python environments.
Virtualenv is a tool to create isolated Python projects. You can think of it as a cleanroom, isolated from other versions of Python and libraries.
Enter this command into the terminal:
sudo pip install virtualenv
Navigate to where you want to store your code, e.g., navigate to your project folder for which you want to create a separate virtual environment.
Create a new directory
mkdir my_project && cd my_project
Now, inside my_project folder, create a new virtualenv
virtualenv venv
here ‘venv’ is the name of the virtual environment getting created
source venv/bin/activate
deactivate
python --version
pip install -r requirements.txt
pip list
Pipenv is a Python virtual environment management tool. This is a tool that combines virtual environments with package management. It creates a new virtual environment for each project and automatically installs the required packages from a Pipfile. It’s designed to simplify the process of managing dependencies for your projects and provides a simpler interface than virtualenv.
pip install pipenv
Once you’ve done that, you can effectively forget about pip
since Pipenv essentially acts as a replacement.
virtualenv -p python3 .venvpipenv install
If .venv
folder is not created/not found, then pipenv creates a virtual environment in the default location on your system. Now, two new files, the [Pipfile](https://github.com/pypa/pipfile)
(which is meant to replace requirements.txt
) and the Pipfile.lock
(which enables deterministic builds) will get created.
pipenv shell
This will create a virtual environment using the .venv folder in your project folder.
pipenv check
This will scan your dependency graph for known security vulnerabilities!
pipenv lock -r
This will convert Pipfile
and Pipfile.lock
into a requirements.txt
file very easily.
In this tutorial, we learned how Python virtual environments avoid conflicts between dependencies of different projects or system-wide. Also, we learned how to work on distinct projects with different dependencies by switching between these self-contained environments using the two simple but powerful methods.
Happy to share my personal experiences!