How to create venv python

How to create venv python

Virtual environments for absolute beginners — what is it and how to create one (+ examples)

A deep dive into Python virtual environments, pip and avoiding entangled dependencies

If you work on a lot of different projects then you’ll recognize the dependency-hell of multiple projects requiring multiple versions, of multiple packages. You can’t just install all packages globally, how do you keep track? Also what happens when projectA needs PackageX_version1 and ProjectB needs PackageX_version2? How do you stay sane when everything is one big jumbled spaghetti-like mess of interdependency?

In this article I’ll try to convince that using a venv (virtual environment) is the way to keep dependencies separate from other projects. We’ll start with defining what a venv is, what it does and why you need it. Then we’ll create one and see all of its benefits. At the end we’ll have some basic rules to keep dependencies in our projects as clean as possible.

1. What is a venv and why would I need one?

What happens when one of your projects need a package with a different version than an other project? What happens when you update a package for one project: will it ruin your code in another project that depends on that package? How do you share your code with others?

To get an idea of what a venv is we’re going to cut it up into two parts: virtual and environment.

Environment

An environment you’re already familiar with. When you install Python3.10 for example then you don’t just install the Python engine, also pip gets installed. When you use pip to install a package it ends up in the Scripts folder in the directory where you installed Python. This is your environment: Python 3.10 with all of the installed packages.

If you run your program like python main.py this happens:

This global installation of Python is your only environment if you do not make use of virtual environments. You can see that keeping all of your projects’ dependencies bundled up in one big box can be dangerous. Time to split this up into virtual environments.

Virtual

I like to think of a venv as creating a whole new, somewhat lighter environment specifically for this project. We’ll see in the coming parts that when you create a venv for your project you actually install Python, pip and the dependencies-folder anew for this specific project. This code doesn’t reside in your default Python path (e.g. C:\Program Files\Python39 ) but can be installed anywhere, for example in your project folder (e.g. C:\myProject\weatherApp\venv ).

Sharing and building the environment

Once you have a virtual environment, you can tell it to create a list for you of all of the packages it contains. Then, when someone else wants to use your code, they can create a venv of their own and use this list to install all the packages, with the right versions all at once. This makes it very easy to share your code with others (via git, mail or usb-stick).

2. Creating a virtual environment

Let’s create our virtual environment! In the steps below we’ll make sure that a virtual environment can be created. For this part it is recommended to read the article if you are inexperienced or unfamiliar with using a terminal. We’ll use a Python package called virtualenv to create our venvs.

Виртуальная среда Python – Основы

How to create venv python. Смотреть фото How to create venv python. Смотреть картинку How to create venv python. Картинка про How to create venv python. Фото How to create venv python

В данной статье мы рассмотрим, как использовать виртуальную среду для создания и управлять ими отдельно в ваших проектах Python, используя разные версии Python для выполнения, а также рассмотрим, как хранятся и разрешаются зависимости Python.

Зачем нужна виртуальная среда?

Python, как и большая часть других современных языков программирования, имеет собственный, уникальный способ загрузки, хранения и разрешения пакетов (или модулей). Это имеет свои преимущества, однако были принятые некоторые интересные решения, на счет хранения и разрешения пакетов, которые привели к определенным проблемам, а именно: как и где эти пакеты хранятся?

Содержание

Существует несколько разных расположений, в которых хранятся пакеты, которые можно установить в вашей системе. Например, большая часть системных пакетов хранятся в дочернем каталоге пути, который, в свою очередь, хранится в sys.prefix.

Есть вопросы по Python?

На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!

Telegram Чат & Канал

Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!

Паблик VK

Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!

На Mac OS X, вы можете легко найти, где именно sys.prefix указывает на использование оболочки Python:

К нашей статье в большей мере относятся сторонние пакеты, установленные при помощи easy_install или pip, обычно располагаются в одном из каталогов, на которую указывает site.getsitepackages:

Зачем нам все эти детали?

Очень важно иметь представление об этом, так как по умолчанию, каждый объект вашей системы будет использовать одинаковые каталоги для хранения и разрешения пакетов (сторонних библиотек. На первый взгляд это не выглядит чем-то значительным. Это так, но только в отношении системных пакетов, являющихся частью стандартной библиотеки Python – но сторонние пакеты – это другое дело.

Представим следующий сценарий, где у вас есть два проекта: проект А и проект Б, которые оба имеют зависимость от одной и той же библиотеки – проект В. Проблема становится явной, когда мы начинаем запрашивать разные версии проекта В. Может быть так, что проект А запрашивает версию 1.0.0, в то время как проект Б запрашивает более новую версию 2.0.0, к примеру.

Это большая проблема Python, поскольку он не может различать версии в каталоге «site-packages». Так что обе версии 1.0.0 и 2.0.0 будут находиться с тем же именем в одном каталоге:

И так как проекты хранятся в соответствии с их названиями, то нет различий между версиями. Таким образом, проекты А и Б должны будут использовать одну и ту же версию, что во многих случаях неприемлемо.

Тут-то и вступает в игру виртуальная среда (вместе с инструментами virtualenv/ven)

Что такое виртуальная среда?

В корне своем, главная задача виртуальной среды Python – создание изолированной среды для проектов Python.

Каждый проект может иметь свои собственные зависимости, вне зависимости от того, какие зависимости у другого проекта.

И так, в нашем небольшом примере вверху, нам просто нужно создать раздельную виртуальную среду для проектов А и Б. Каждая среда, в свою очередь, сможет зависеть от любой версии проекта В, независимо друг от друга.

Это хорошо тем, что у нас нет ограничений на то, в скольких экземплярах будет наша виртуальная среда, так как они являются обычными каталогами, в которых содержится несколько скриптов. Плюс, их очень легко создать при помощи инструментов командной строки virtualenv или pyenv.

Использование виртуальной среды

Перед тем, как начать: если вы не пользуетесь Python 3, вам нужно будет установить инструмент virtualenv при помощи pip:

Если вы используете Python 3, у вас уже должен быть модуль venv, установленный в стандартной библиотеке.

Предположим, что вы пользуетесь последней версией инструмента venv, так как между ним и virtualenv существует несколько различий в отношении команд. По большому счету, это два весьма разных инструмента.

Начнем с создания нового каталога, с которым мы будем работать:

Создание новой виртуальной среды внутри каталога:

По умолчанию, это не включает в себя ни один из существующих сторонних пакетов.

Подход venv в Python 3 обладает преимуществом, которое вынуждает вас использовать определенную версию интерпретатора Python 3, который будет использован для создания виртуальной среды. Таким образом, вы избегаете недоразумений при выяснении, какая инсталляция Python базируется в новой виртуальной среде.

В примере выше, эта команда создает каталог под названием «env», структура каталога которого схожа со следующей:

Что находится в этих папках?

Далее, у нас есть копии или символические ссылки нескольких различных инструментов Python. Эти файлы используются для обеспечения того, чтобы команды и код Python выполнялись в контексте нынешней среды, таким образом, достигается изоляция от глобальной среды. Мы рассмотрим это детальнее в следующем разделе.

Более интересные сейчас – скрипты activate в папке bin. Эти скрипты используются для настройки вашей оболочки для использования исполняемого файла среды Python и его сайтовых пакетов по умолчанию.

Чтобы использовать эти пакеты (или ресурсы) среды в изоляции, вам нужно «активировать» их. Чтобы сделать это, просто запустите:

Обратите внимание на то, что ваше приглашение командной строки теперь носит префикс вашей среды (в нашем случае – env). Это индикатор того, что env в данный момент активен, что в свою очередь говорит о том, что выполнимые файлы Python используют пакеты и настройки только этой среды.

Чтобы показать изолированный пакет в действии, мы можем использовать модуль bcrypt в качестве примера. Скажем, что модуль bcrypt установлен где-нибудь в системе, но не в нашей виртуальной среде.

Теперь ваш сеанс оболочки вернулся в норму, а команда python ссылается на общую установку Python. Помните: это можно делать когда угодно, после закрытия определенной виртуальной среды.

Теперь установим bcrypt и используем его для хеширования пароля:

Что произойдет, если мы попробуем ту же команду, когда виртуальная среда активна?

В одном примере, у нас есть доступный нам bcrypt, а в другом его нет. Это тот тип разделения, который мы ищем для виртуальной среды, и мы к нему пришли.

Как работает виртуальная среда?

Что именно имеется ввиду под «активировать» среду? Понимание того, что именно происходит под капотом, может быть очень важно для разработчика, особенно когда вам нужно понять выполнение виртуальной среды, разрешение зависимостей, и так далее.

Чтобы объяснить, как это работает, для начала проверим расположения разных исполняемых файлов python. С «деактивированной» средой запускаем:

Теперь активируем и снова запустим команду:

Активировав среду, мы теперь получаем другой путь к исполнимому файлу python, так как в активной среде, переменная среды $PATH несколько отличается.

Обратите внимание на разницу между первым путем в $PATH до и после активации:

В последнем примере, каталог bin нашей виртуальной среды теперь находится в начале пути. Это значит, что это первый каталог в поиске, когда мы запускаем исполняемый файл в командной строке. Таким образом, оболочка использует экземпляр нашей виртуальной среды в Python, а не в системной версии.

Другие пакеты, связывающие Python, такие как Anaconda, также могут выполнять манипуляции с вашим путем, если вы активируете их. Просто имейте это ввиду на случай, если вы столкнетесь с проблемами, связанными с другими виртуальными средами. Проблема может возникнуть при активации нескольких сред одновременно.

Это наталкивает на вопросы:

Это можно объяснить тем, как Python запускается и где он расположен в системе. Нет разницы между двумя исполняемыми файлами Python. Суть заключается в расположении каталога

Когда Python запускается, он ищет путь своего двоичного файла (в виртуальной среде он является копией или символической ссылке системного бинарного файла Python). Далее, он устанавливает расположение sys.prefix и sys.exec_prefix согласно с этим расположением, опуская часть bin в пути.

Путь, находящийся в sys.prefix далее используется для поиска каталога site-packages, путем поиска по связанного с ним пути lib/pythonX.X/site-packages/, где Х.Х – это версия используемого вами Python.

В нашем примере, бинарный файл расположен в /Users/michaelherman/python-virtual-environments/env/bin, это значит, что sys.prefix может быть /Users/michaelherman/python-virtual-environments/env, следовательно, используемый каталог site-packages может быть /Users/michaelherman/python-virtual-environments/env/lib/pythonX.X/site-packages. Наконец, этот путь наложен в массиве sys.path, который содержит все расположения, которые пакет может использовать.

Управление виртуальной средой при помощи virtualenvwrapper

Несмотря на то, что виртуальная среда определенно решает ряд проблем с управлением пакетами, она не идеальна. После создания нескольких виртуальных сред, вы обнаружите, что они создают некоторые проблемы сами по себе, большая часть которых вращается вокруг управления самими виртуальными средами. Чтобы помочь с этим, был создан инструмент virtualenvwrapper, который представляет собой набор оберточных скриптов вокруг основного инструмента virtualenv.

Самые полезные функции virtualenvwrapper:

Некоторые функции могут показаться узкими, или незначительными, вы быстро поймете, что они – это отличные инструменты для вашего рабочего ритма.

Перед началом, вы можете скачать обёртку при помощи pip:

Python Virtual Environment Tutorial

What is a Python Virtual Environment?

Basically a Python virtual environment is a folder with a few scripts in it that allows you to create an isolated environment to work on your project allowing you to install different versions of Python and other packages different than your system version.

In this Python virtual environment tutorial I will show you how to manage different projects that might require different versions of packages or modules by creating a virtual environment.

Python Virtual Environment Ubuntu

This will all be done on Ubuntu but the principles are the same for other operating systems

By default all packages or modules are installed in the same location (this location is dependent on your system).

If you are writing a project that requires version 1.0 of a certain package and another project that requires version 1.5 of a certain package you have a bit of a problem.

This is where a Python virtual environment comes in.

There is no limit to how many virtual environments you can have as it’s just a folder.

You can use virtualenv or venv to create this virtual environment.
Both perform the same job but venv is installed by default with Python3 and virtualenv has to be installed as a package.

If you are running Python2 you need to install virtualenv, if you are running Python 3 then venv is the way to go.

How do you create a virtual environment in Python 3 using venv?

First I would recommend you create a folder on your system where you have all your virtual environments.

To create venv use the command

So if I wanted to create a virtual environment called env1 I would type

If I now do an ls in my VENVS folder I will see another folder called env1

How to create venv python. Смотреть фото How to create venv python. Смотреть картинку How to create venv python. Картинка про How to create venv python. Фото How to create venv python

To use this you now have to go into the folder and activate it, (start virtual environment python) this will setup your shell so use the environments Python executable and it’s site packages by default.

How to Activate Python Virtual Environment

From within my VENVS folder I enter the command

You will now observe that your prompt changes

How to create venv python. Смотреть фото How to create venv python. Смотреть картинку How to create venv python. Картинка про How to create venv python. Фото How to create venv python

I am now working within an isolated environment. First let’s see what version of Python we are running with which python

How to create venv python. Смотреть фото How to create venv python. Смотреть картинку How to create venv python. Картинка про How to create venv python. Фото How to create venv python

We actually are running an isolated version of Python from within this folder.

Then we will see what packages we have installed with pip3 freeze

How to create venv python. Смотреть фото How to create venv python. Смотреть картинку How to create venv python. Картинка про How to create venv python. Фото How to create venv python

You can see there are none – compared to if we exit the venv this list would have all the packages.

How to exit VENV

To exit a virtual environment you use the command deactivate

How to create venv python. Смотреть фото How to create venv python. Смотреть картинку How to create venv python. Картинка про How to create venv python. Фото How to create venv python

Best Python Virtual Environment

If you are just starting out learning Python you might not have a need to create a virtual environment, but as you write more code and different projects with different dependencies, you will find you are using the venv command every day! The best way or tool to create a virtual environment is really the one that works for you.

I use Python for Network Automation if you like these posts and want to learn more check my other posts.

Frequently asked questions

What is a virtual environment in Python?

In simple terms a virtual environment is a folder where you can run an isolated environment so you can install different versions of Python and or packages and libraries, so they do not interfere with your system versions of the same packages.

Is VENV the same as virtualenv?

They are nearly interchangeable, the main difference is virtualenv supports older versions of Python i.e 2.x and VENV is now the standard library in Python 3

Create virtual environment using venv | Python

A virtual environment is a tool that helps to keep dependencies required by different projects separate by creating isolated python virtual environments for them. This is one of the most important tools that most of the Python developers use.

Need of virtual environment

Imagine a scenario where a web app is hosted on a cloud hosting service provider with a python development environment. The configuration for the web app comes with an option for installing the newest version of the Flask web framework. Suppose, the web app is created on the local system with an older version of the framework and as soon as it is uploaded on the site, there will be a version conflict as some of the modules used are depreciated in the latest versions of Flask.

Use of virtual environment

The above scenario can be solved using virtual environment. Python development environments can be separated by making use of some virtual environment. A virtual environment, here, is an isolated Python installation that allows to manage dependencies and work on separate Python projects without affecting other projects. When a virtual environment is created, it creates a separate folder from the global Python or other virtual environments and copies Python into it along with a site-packages folder among a couple of others. For older versions of Python, virtual machines require installing a third-party tool called virtualenv. It’s been integrated into newer versions of Python3 under the module venv. To know more about virtualenv click here.

Implementing venv

First, check whether the pip has the same version of the interpreter as that on the system and where the Python environment currently resides: To check where the python currently resides type the below command in the terminal.

Output:

To create a virtualenv use the following command:

After running this command, a directory named venv will be created. This is the directory which contains all the necessary executables to use the packages that a Python project would need. This is where Python packages will be installed. To list the files in the folder type below command in the terminal:

Output: How to create venv python. Смотреть фото How to create venv python. Смотреть картинку How to create venv python. Картинка про How to create venv python. Фото How to create venv pythonThe pip command still points to the global environment. We need to explicitly activate the created virtual environment to configure the current shell session to use pip commands from the virtualenv folder and don’t end up installing packages in the global environment: To activate venv first change the directory to venv\Scripts.

After changing the directory type the below command.

Once the virtual environment is activated, the name of your virtual environment will appear on left side of terminal. This will let you know that the virtual environment is currently active. In the image below, venv named virtual environment is active.

(Note: try “./activate” instead of “activate” if using powershell terminal) How to create venv python. Смотреть фото How to create venv python. Смотреть картинку How to create venv python. Картинка про How to create venv python. Фото How to create venv pythonThe Python interpreter as well would run the version from the virtual environment and not the global one. We can verify where the Python environment currently resides by below command:

Output:

The virtual environment is an almost clean Python environment. Run pip list to see a list with packages installed: Output: How to create venv python. Смотреть фото How to create venv python. Смотреть картинку How to create venv python. Картинка про How to create venv python. Фото How to create venv pythonNow you can install dependencies related to the project in this virtual environment. For example if you are using Django 1.9 for a project, you can install it like you install other packages.

Once you are done with the work, you can deactivate the virtual environment by the following command:

How to create venv python. Смотреть фото How to create venv python. Смотреть картинку How to create venv python. Картинка про How to create venv python. Фото How to create venv python

Now you will be back to system’s default Python installation.

Python/Virtual environment

virtualenv is a tool used to create an isolated workspace for a Python application. It has various advantages such as the ability to install modules locally, export a working environment, and execute a Python program in that environment.

Contents

Overview

A virtual environment is a directory into which some binaries and shell scripts are installed. The binaries include python for executing scripts and pip for installing other modules within the environment. There are also shell scripts (one for bash, csh, and fish) to activate the environment. Essentially, a virtual environment mimics a full system install of Python and all of the desired modules without interfering with any system on which the application might run.

Installation

Python 3.3+ comes with a module called venv. For applications that require an older version of Python, virtualenv must be used.

Packages

Install one of these packages from the official repositories to use a Python virtual environment.

Usage

All three tools use a similar workflow.

Creation

Use venv or virtualenv to create the virtual environment within your project directory. Be sure to exclude the venv directory from version control—a copy of pip freeze will be enough to rebuild it.

This tool is provided by python (3.3+):

virtualenv

Activation

Use one of the provided shell scripts to activate and deactivate the environment. This example assumes bash is used.

Once inside the virtual environment, modules can be installed with pip and scripts can be run as normal.

To exit the virtual environment, run the function provided by bin/activate :

Python versions

By default, virtual environments are created using system Python. The bin/python binary is just a symlink to system python:

pypy3 can also be used:

virtualenvwrapper

Installation

Install the python-virtualenvwrapper package and add the following lines to your

Re-open your console to apply changes. The WORKON_HOME directory will be created automatically.

Basic usage

Activate the virtual environment:

Install some package inside the virtual environment (say, Django):

After you have done your things, leave the virtual environment:

Pipenv

pipenv allows better managed CLI interactions by providing a single program that does all the functions of the above tools.

Installation

Basic usage

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *