Don’t know how to create a virtual environment in Python? Let me tell you how!
How to Create Virtual Environment in Python?
A Python virtual environment is an isolated workspace that allows you to install and manage packages independently from the system Python installation. This ensures that project-specific dependencies do not interfere with other projects or the system.
Pre-requisites
Before creating a virtual environment in Python, ensure that you have already installed Python and pip on your system. Otherwise, follow these steps:
1) Install Python
First of all, go to python.org and download the Python installer for Windows:
Once downloaded, run the Python installer:
Check the second box to automatically set the system’s path environment variable for Python:
Next, open the command prompt and check for the Python version to verify its installation:
python --version
2) Install pip
To download pip, launch the command prompt and execute the command below:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
Then, run this script to install pip:
python get-pip.py
Lastly, to ensure its successful installation, run:
pip --version
Creating a Python Virtual Environment
Once done with the prerequisites, create a virtual environment in Python via this procedure.
Step 1: Install virtualenv
Install the “virtualenv” module used for creating a Python virtual environment other than the actual one:
pip install virtualenv
Make sure that it is successfully installed:
virtualenv --version
Step 2: Create a Python Virtual Environment
Firstly, move to that particular location where you want to create the Python virtual environment.
Next, use the “virtualenv” module along with the name you want to give to this new virtual environment. Here “python_Project” is my virtual environment’s name:
virtualenv python_Project
As a result of executing the above command, a directory will be created with the mentioned virtual environment’s name:
Step 3: Activate the Python Virtual Environment
Execute the cd command to move to the new virtual environment’s directory:
cd python_Project
After that, run this command:
Scripts\activate
Step 4: Deactivate the Python Virtual Environment (optional)
Deactivate the virtual environment via this command:
deactivate
Conclusion
To create a virtual environment in Python, install Python and pip first. Next, install the “virtualenv” module and confirm its installation. Utilize the virtualenv module to create a Python virtual environment. Once created, you can activate and deactivate this environment via the command prompt or terminal.