Skip to content

Instantly share code, notes, and snippets.

@Denilson-Semedo
Created February 17, 2024 11:34
Show Gist options
  • Save Denilson-Semedo/2b24e1856ccf23ac2fe74069f654eefa to your computer and use it in GitHub Desktop.
Save Denilson-Semedo/2b24e1856ccf23ac2fe74069f654eefa to your computer and use it in GitHub Desktop.

venv | Python Virtual Environment

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.

Creating a Virtual Environment

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

Activating a Virtual Environment

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

Leaving the Virtual Environment

To leave the virtual environment, simply type:

deactivate

Using the Virtual Environment

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

Removing a Virtual Environment

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment