Home > Backend Development > Python Tutorial > Python virtual Environments

Python virtual Environments

王林
Release: 2024-07-28 07:36:43
Original
471 people have browsed it

Python virtual Environments

TL;DR

Essentially this allows you to create an isolated environment for each python application you create. Meaning each application can use difference libraries or even different version of the same library without interfering with each other.

What is VENV

A python virtual environment or VENV is a lightweight self-contained directory tree that contains a Python installation for a particular version of python, plus a number of additional packages.

Each python application you create can use its own virtual environment. This resolves the problem of conflicting requirements between applications.

The venv module is used to create the virtual environment.

How to install venv

pip install virtualenv
Copy after login

Create a virtual environment

python -m venv /path/to/new/virtual/environment
Copy after login

Use a virtual environment

For Linux or Mac OS your new venv can be activated by using this command:

source /path/to/new/virtual/environment/bin/activate
Copy after login

For windows:

\path\to\new\virtual\environment\Scripts\activate.bat
Copy after login

Once activated you should be able to install libraries via pip like you normally would but it will now be installed into you virtual environment

Exiting your virtual environment

Just like with activation venv provides a handy deactivate script. For Linux or Mac OS your new venv can be deactivated by using this command:

deactivate
Copy after login

or if that does not work:

source /path/to/new/virtual/environment/bin/deactivate
Copy after login

For windows:

\path\to\new\virtual\environment\Scripts\deactivate.bat
Copy after login

Why should you use a virtual environment

When you run Python and its libraries from the system, you are restricted to a specific Python version chosen by your operating system. This approach can lead to version conflicts among the libraries when running multiple Python applications on the same installation. Additionally, modifying the system Python may disrupt other OS features that rely on it. Using a virtual environment isolates each application thus solving this problem.

The above is the detailed content of Python virtual Environments. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template