Питон в коробке – venv в python 3.3
Наверняка, большинство из тех, кто разрабатывает или деплоит Python приложения, использует виртуальные окружения. В частности через virtualenv, написанный Ian Bicking.
Идея оказалась так хороша и распространена, что нечто похожее теперь присутствует в Python 3.3 из коробки в виде модуля venv. Он почти такой же, как virtualenv, только немного лучше.
Как это работает?
- в директории с интерпретатором или уровнем выше ищется файл с именем pyvenv.cfg ;
- если файл найден, в нём ищется ключ home, значение которого и будет базовой директорией;
- в базовой директории идёт поиск системной библиотеки (по спец. маркеру os.py );
- если что-то пошло не так – всё откатывается к захардкоженному в бинарнике значению.
Вот и вся суть venv, всё остальное уже обёртка над этим.
Как создать?
Всё очень просто, нужно вызвать через ключ -m модуль venv , либо использовать встроенный скрипт pyvenv:
Скрипт создаст указанную директорию, вместе со всеми родительскими директориями, если потребуется, и построит виртуальное окружение. Это можно делать и в Windows, только вызов будет чуть более многословным:
При создании можно добавлять различные параметры, как, например, включение системных site-packages или использование symlink вместо копирования интерпретатора.
В отличии от virtualenv новый venv требует чтобы создаваемая директория не существовала, либо была пустой. Вероятно, это сделано, чтобы не допускать конфликтов с существующими файлами. Это бага в python 3.3, в 3.4 уже исправлено. (Спасибо, svetlov).
Как использовать?
Можно использовать старый добрый метод активации через bin/activate (Scripts/activate в windows):
А можно и не использовать, достаточно лишь вызвать интерпретатор из окружения и всё сработает автоматически:
Это конечно не сработает для скриптов, запускаемых напрямую через #!/usr/bin/env python3 , для них всё равно нужно будет, как и раньше, делать активацию. Решение есть – о нём чуть ниже.
Обновление
Если в вашей системе обновилась версия python, то виртуальное окружение иногда тоже нужно обновить.
Всё просто – вызываем venv аналогично созданию окружения, добавив ключ —upgrade :
Это произойдёт автоматически, если использовать symlink, но если вы хотите кроме изоляции делать фиксацию версии python и библиотек, я бы рекомендовал делать обновление вручную.
Расширение EnvBuilder
Вся работа по созданию окружения падает на класс venv.EnvBuilder , этот класс написан так, чтобы его можно было расширять.
Например, можно при инициализации окружения ставить туда distribute , pip и необходимые начальные зависимости из requirements.txt . Более сложную логику лучше оставить на совести более предназначенных для этого инструментов, типа buildout или make, но первоначальную настройку можно провести и на уровне EnvBuilder.
При создании окружения используется метод create(self, env_dir) , в исходном классе он выглядит так:
Метод описывает суть всего процесса: создание директории ( ensure_directories ), конфигурацию ( create_configuration ), добавление бинарников питона ( setup_python ) и добавление скриптов активации ( setup_scripts ).
В конце вызывается хук post_setup , в который вы можете добавлять свои действия. Видно, что post_setup выполняется только при создании окружения, а при — upgrade он выполняться не будет. Это легко исправить, добавив ещё один хук:
- context.bin_path — путь к директории с бинарниками и исполняемыми скриптами,
- context.env_dir — путь к директории с созданным окружением,
- context.env_exe — путь к бинарнику внутри окружения.
Соответственно, для запуска python скрипта внутри окружения, можно сделать:
Исполняемые скрипты внутри venv
Вернёмся к проблеме с исполняемыми скриптами внутри виртуального окружения.
В virtualenv для них достаточно было указать интерпретатор через #/usr/bin/env python3 и использовать, не забывая сделать . bin/activate . Если вас такой подход устраивал, то вы можете им продолжать пользоваться и в venv .
Есть и новый путь. Внутри EnvBuilder реализован метод install_scripts(self, context, path) , который автоматизирует копирование скриптов и бинарников в создаваемое окружение. В path необходимо передать путь к директории с вложенными поддиректориями «common», «nt», «posix» и т.д. В поддиректории, в свою очередь, положить необходимые скрипты или бинарники. В «common» скрипты для всех платформ, в «nt» – для Windows, «posix» – для Linux, Mac OS X и других posix систем.
- __VENV_DIR__
- __VENV_NAME__
- __VENV_BIN_NAME__
- __VENV_PYTHON__
Пример шаблона запускаемого python скрипта:
__VENV_PYTHON__ будет заменено на полный путь к интерпретатору python в виртуальном окружении.
После установки такого скрипта через install_scripts , его можно будет запускать, без необходимости активации окружения через bin/activate.
Виртуальное окружение Python (venv)
В се сторонние пакеты устанавливаются менеджером PIP глобально. Проверить это можно просто командой pip show <имя_пакета> .
# pip3 show pytest Name: pytest Version: 5.3.2 Summary: pytest: simple powerful testing with Python Home-page: https://docs.pytest.org/en/latest/ Author: Holger Krekel, Bruno Oliveira, Ronny Pfannschmidt, . License: MIT license Location: /usr/local/lib/python3.8/site-packages Requires: more-itertools, pluggy, py, wcwidth, attrs, packaging Required-by:
Location — путь до ваших глобальных пакетов.
В большинстве случаев, устанавливать пакеты глобально — плохая идея ♂️ Почему? Рассмотрим простой пример:
Допустим у нас есть два проекта: " Project A" и " Project B" . Оба проекта зависят от библиотеки Simplejson . Проблема возникает, когда для "Project A" нужна версия Simplejson 3.0.0, а для проекта "Project B" — 3.17.0. Python не может различить версии в глобальном каталоге site-packages — в нем останется только та версия пакета, которая была установлена последней.
Решение данной проблемы — создание виртуального окружения (virtual environment).
Основная цель виртуального окружения Python — создание изолированной среды для python-проектов
Это означает, что каждый проект может иметь свои собственные зависимости, независимо от других проектов.
Настройка виртуального окружения
Один из самых популярных инструментов для создания виртуального окружения — virtualenv . Однако в данной статье мы будем рассматривать более свежий инструмент venv .
Устанавливать venv не нужно — он входит в стандартную библиотеку Python
Создание
Для создания виртуального окружения, перейдите в директорию своего проекта и выполните:
python -m venv venv
Флаг -m указывает Python-у запустить venv как исполняемый модуль. venv/ — название виртуального окружения (где будут храниться ваши библиотеки).
В результате будет создан каталог venv/ содержащий копию интерпретатора Python, стандартную библиотеку и другие вспомогательные файлы.
Новые пакеты будут устанавливаться в venv/lib/python3.x/site-packages/
Активация
Чтобы начать пользоваться виртуальным окружением, необходимо его активировать:
- venv\Scripts\activate.bat — для Windows;
- source venv/bin/activate — для Linux и MacOS.
source выполняет bash-скрипт без запуска дополнительного bash-процесса.
Проверить успешность активации можно по приглашению оболочки. Она будет выглядеть так:
Также новый путь до библиотек можно увидеть выполнив команду:
python -c "import site; print(site.getsitepackages())"
Интересный факт: в виртуальном окружении вместо команды python3 и pip3, можно использовать python и pip
Автоматическая активация
В некоторых случаях, процесс активации виртуального окружения может показаться неудобным (про него можно банально забыть ♀️).
На практике, для автоматической активации перед запуском скрипта, создают скрипт-обертку на bash :
#!/usr/bin/env bash source $BASEDIR/venv/bin/activate python $BASEDIR/my_app.py
Теперь можно установить права на исполнение и запустить нашу обертку:
chmod +x myapp/run.sh ./myapp/run.sh
Деактивация
Закончив работу в виртуальной среде, вы можете отключить ее, выполнив консольную команду:
Альтернативы venv
На данный момент существует несколько альтернатив для venv:
- — это pipfile, pip и virtualenv в одном флаконе;
- pyenv — простой контроль версий Питона; — новый менеджер для управления зависимостями;
- autoenv — среды на основе каталогов;
- pew — инструмент для управления несколькими виртуальными средами, написанными на чистом Python;
- rez — интегрированная система конфигурирования, сборки и развертывания пакетов для программного обеспечения.
Стоит ли использовать виртуальное окружение в своей работе — однозначно да. Это мощный и удобный инструмент изоляции проектов друг от друга и от системы. С помощью виртуального окружения можно использовать даже разные версии Python!
Однако рекомендуем присмотреться к более продвинутым вариантам, например к pipenv или poetry .
Python venv: How To Create, Activate, Deactivate, And Delete
Python virtual environments allow you to install Python packages in an isolated location from the rest of your system instead of installing them system-wide. Let’s look at how to use the Python venv, short for Python virtual environment, also abbreviated as virtualenv.
In this article, you will learn:
- The advantages of using virtual environments
- How to create a venv
- How to activate and deactivate it
- Different ways to delete or remove a venv
- How a venv works internally
If you want to learn about virtual environments thoroughly and get some hands-on practice, please have a look at my Python Fundamentals II course. It’s a deep dive into modules, packages, virtual environments, and package managers.
Table of contents
Why you need virtual environments
There are multiple reasons why virtual environments are a good idea, and this is also the reason why I’m telling you about them before we continue to the part where we start installing 3rd party packages. Let’s go over them one by one.
Preventing version conflicts
You could argue that you’re very efficient if you install third-party packages system-wide. After all, you only need to install it once and can use the package from multiple Python projects, saving you precious time and disk space. There’s a problem with this approach that may start to unfold weeks or months later, however.
Suppose your project, Project A , is written against a specific version of library X . In the future, you might need to upgrade library X. Say, for example, you need the latest version for another project you started, called Project B. You upgrade library X to the latest version, and project B starts working fine. Great! But once you did this, it turns out your Project A code broke badly. After all, APIs can change significantly on major version upgrades.
A virtual environment fixes this problem by isolating your project from other projects and system-wide packages. You install packages inside this virtual environment, specifically for the project you are working on.
Easy to reproduce and install
Virtual environments make it easy to define and install the packages specific to your project. Using a requirements.txt file, you can define exact version numbers for the required packages to ensure your project will always work with a version tested with your code. This also helps other users of your software since a virtual environment helps others reproduce the exact environment for which your software was built.
Works everywhere, even when not root
If you’re working on a shared host, like those at a university or a web hosting provider, you won’t be able to install system-wide packages since you don’t have the administrator rights to do so. In these places, a virtual environment allows you to install anything you want locally in your project.
Virtual environments vs. other options
There are other options to isolate your project:
- In the most extreme case, you could buy a second PC and run your code there. Problem fixed! It was a bit expensive, though!
- A virtual machine is a much cheaper option but still requires installing a complete operating system—a bit of a waste as well for most use cases.
- Next in line is containerization, with the likes of Docker and Kubernetes. These can be very powerful and are a good alternative.
Still, there are many cases when we’re just creating small projects or one-off scripts. Or perhaps you just don’t want to containerize your application. It’s another thing you need to learn and understand, after all. Whatever the reason is, virtual environments are a great way to isolate your project’s dependencies.
How to create a Python venv
There are several ways to create a Python virtual environment, depending on the Python version you are running.
Before you read on, I want to point you to two other tools, Python Poetry and Pipenv. Both these tools combine the functionality of tools that you are about to learn: virtualenv and pip. On top of that, they add several extras, most notably their ability to do proper dependency resolution.
To better understand virtual environments, I recommend you learn the basics first though from this article. I just want to ensure that you know that there are nicer ways to manage your packages, dependencies, and virtual environments.
Python 3.4 and above
If you are running Python 3.4+, you can use the venv module baked into Python:
This command creates a venv in the specified directory and copies pip into it as well. If you’re unsure what to call the directory: venv is a commonly seen option; it doesn’t leave anyone guessing what it is.
A little further in this article, we’ll look closely at the just-created directory. But let’s first look at how to activate this virtual environment.
All other Python versions
The alternative that works for any Python version is using the virtualenv package. You may need to install it first with pip install:
Once installed, you can create a virtual environment with:
Python venv activation
How you activate your virtual environment depends on the OS you’re using.
Windows venv activation
To activate your venv on Windows, you need to run a script that gets installed by venv. If you created your venv in a directory called myenv , the command would be:
Linux and MacOS venv activation
On Linux and MacOS, we activate our virtual environment with the source command. If you created your venv in the myvenv directory, the command would be:
That’s it! We’re ready to rock! You can now install packages with pip, but I advise you to keep reading to understand the venv better first.
My course Python Fundamentals II extensively covers:
- creating your own modules and packages,
- Using virtual environments
- Leveraging Python package managers like Poetry and Pipenv to make your life as a programmer easier.
Advance your productivity as a Python programmer and join my course today!
How a Python venv works
When you activate a virtual environment, your PATH variable is changed. On Linux and MacOS, you can see it for yourself by printing the path with echo $PATH . On Windows, use echo %PATH% (in cmd.exe) or $Env:Path (in PowerShell). In my case, on Windows, it looks like this:
C:\Users\erik\Dev\venv\Scripts;C:\Program Files\PowerShell\7;C:\Program Files\AdoptOpen.
It’s a big list, and I only showed the beginning of it. As you can see, the Scripts directory of my venv is put in front of everything else, effectively overriding all the system-wide Python software.
So what does this PATH variable do?
When you enter a command that can’t be found in the current working directory, your OS starts looking at all the paths in the PATH variable. It’s the same for Python. When you import a library, Python starts looking in your PATH for library locations. And that’s where our venv-magic happens: if your venv is there in front of all the other paths, the OS will look there first before looking at system-wide directories like /usr/bin . Hence, anything that gets installed in our venv is found first, and that’s how we can override system-wide packages and tools.
What’s inside a venv?
If you take a look inside the directory of your venv, you’ll see something like this on Windows:
And on Linux and MacOS:
Virtualenv directory tree
You can see that:
- The Python command is made available both as python and python3 (on Linux and MacOS), and the version is pinned to the version with which you created the venv by creating a symlink to it.
- On Windows, the Python binary is copied over to the scripts directory.
- All packages you install end up in the site-packages directory.
- We have activation scripts for multiple shell types (bash, csh, fish, PowerShell)
- Pip is available under the names pip and pip3, and even more specifically under the name pip3.7 because I had a Python 3.7 installation at the time of writing this.
Deactivate the Python venv
Once you have finished working on your project, it’s a good habit to deactivate its venv. By deactivating, you basically leave the virtual environment. Without deactivating your venv, all other Python code you execute, even if it is outside your project directory, will also run inside of the venv.
Luckily, deactivating your virtual environment couldn’t be simpler. Just enter this: deactivate . It works the same on all operating systems.
Deleting a Python venv
You can completely remove a virtual environment, but how you do that depends on what you used to create the venv. Let’s look at the most common options.
Delete a venv created with Virtualenv or python -m venv
There’s no special command to delete a virtual environment if you used virtualenv or python -m venv to create your virtual environment, as is demonstrated in this article. When creating the virtualenv, you gave it a directory to create this environment in.
If you want to delete this virtualenv, deactivate it first and then remove the directory with all its content. On Unix-like systems and in Windows Powershell, you would do something like:
Delete a venv with Pipenv
If you used Pipenv to create the venv, it’s a lot easier. You can use the following command to delete the current venv:
Make sure you are inside the project directory. In other words, the directory where the Pipenv and Pipenv.lock files reside. This way, pipenv knows which virtual environment it has to delete.
If this doesn’t work, you can get a little nastier and manually remove the venv. First, ask pipenv where the actual virtualenv is located with the following command:
It will output the path to the virtual environment and all of its files and look similar to the example above. The next step is to remove that entire directory, and you’re done.
Delete a venv with Poetry
If you created the virtualenv with Poetry, you can list the available venvs with the following command:
You’ll get a list like this:
You can remove the environment you want with the poetry env remove command. You need to specify the exact name from the output above, for example:
Conclusion
You learned how to create, activate, deactivate, and delete virtual environments. We also looked behind the curtains to see why and how a venv works. Now that you know how to create a venv, you need to learn how to install packages inside of it. After that, I strongly recommend you to learn about Pipenv or Poetry. These tools combine the management of your virtual environment with proper package and dependency management.
Keep learning
- Next up: how to install packages with pip inside your venv is a better way of managing your venv and packages.
- Learn the most common Linux commands (like cd, mkdir, pwd, etcetera) : If you want to know all the details and command-line options
Related posts you might like
Python Courses
Are you enjoying this free tutorial? Please also have a look at my premium courses. They offer a superior user experience with small, easy-to-digest lessons and topics, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.
Python Fundamentals I is a course for beginners that will get you started with Python in no time. Learn all the essentials, test your progress with quizzes and assignments, and bring it all together with the final course project!