by Team Codeasify
951
Table of Contents
In order to create a Python virtual environment, you must have Python installed on your computer.
If you don't already have Python installed, you can download it from the Python website (https://www.python.org/) and install it according to the instructions provided or you can follow this amazing blog.
Once you have Python installed, you can create a virtual environment with two methods:
- venv: Module, which is included in Python by default.
-
virtualenv: Package, which is a third-party package that provides additional functionality for managing virtual environments.
Let's take a closer look at each of them one by one.
How to create Python virtual environment with virtualenv?
It is necessary to have Python and pip (the Python package manager) installed on your system before installing virtualenv.
Once you have Python and pip installed, you can use pip to install virtualenv by running the following command in a terminal or command prompt:
pip install virtualenv
This will install virtualenv on your system.
To create a virtual environment with virtualenv, navigate to the directory where you want to create the virtual environment and run the following command:
virtualenv venv
Replace venv with the name you want to give your virtual environment.
This will create a new directory called venv in the current directory, which will contain the files and directories needed for the virtual environment.
To activate the virtual environment, run the following command:
source venv/bin/activate
Replace venv with the name of your virtual environment.
Once the virtual environment is activated, you should see the name of your virtual environment in parentheses at the beginning of the terminal prompt, like this: (venv) $. This indicates that the virtual environment is active and that any Python packages you install will be installed in the virtual environment, rather than in the global Python environment.
To deactivate the virtual environment, run the following command:
deactivate
This will take you out of the virtual environment, and you will no longer see the virtual environment's name in parentheses at the beginning of the terminal prompt.
Now let's set with venv default module.
How to create Python virtual environment with venv?
The venv module, included by default in Python, allows you to create a virtual environment once you have Python installed. The steps are as follows:
Run the following command to create a virtual environment:
python -m venv myenv
To activate the virtual environment, run the following command:
source myenv/bin/activate
To deactivate the virtual environment, run the following command:
deactivate
We hope this helps you in some way! We would be glad to answer any questions you may have.