Python Virtual Environment is a tool to keep the dependencies required by different projects in separate places. The venv module provides support for creating lightweight “virtual environments” with their own site directories, optionally isolated from system site directories. Each virtual environment has its own Python binary (which matches the version of the binary that was used to create this environment) and can have its own independent set of installed Python packages in its site directories.
To create a virtual environment, decide upon a directory where you want to place it, and run the venv module as a script with the directory path:
python3 -m venv /path/to/new/virtual/environment
This will create the /path/to/new/virtual/environment
directory if it doesn’t exist, and also create directories inside it containing a copy of the Python interpreter, the standard library, and various supporting files.
A common directory location for a virtual environment is .venv. This name keeps the directory typically hidden in your shell and thus out of the way while giving it a name that explains why the directory exists.
python3 -m venv .venv
Once you’ve created a virtual environment, you may activate it. On Windows, run:
.venv\Scripts\activate
On Unix or MacOS, run:
source .venv/bin/activate
To leave the virtual environment, simply type:
deactivate
Once a virtual environment has been activated, the Python interpreter installed in it can be used to run scripts and install modules. For example, to install a module, use the pip tool:
pip install requests
To remove a virtual environment, simply delete the directory where it was created. For example:
rm -rf /path/to/virtual/environment
Alternatively, if you have created the virtual environment using the venv module, you can use the following command:
python3 -m venv --clear /path/to/virtual/environment
This will remove the contents of the virtual environment directory, effectively cleaning it up. However, it's worth noting that this command won't delete the directory itself, so you may still need to remove it manually if desired.