Как установить другую версию python

от admin

Использование нескольких версий Python на unix-подобных операционных системах

Python как язык постоянно развивается. Ветка Py2 уже не поддерживается официально. Однако до сих пор существуют окружения, где приходится использовать Py2 и даже не свежий 2.7.x, а что-то постарее. Да и Python 3.x нынче — это большое семейство версий, кое-где несовместимых между собой, в т.ч. и синтаксически! Поэтому практикующий питонист широкого профиля должен понимать, как на одной машине иметь несколько версий среды исполнения. Даже если "в продакшне" и используется какой-нибудь Docker!

Установка Python из репозиториев пакетов операционной системы

Если вам повезло, то в репозитории пакетов ОС будет нужная версия Python, и вы сможете её установить с помощью команды вроде sudo apt-get install python3.5 . Однако достаточно старые дистрибутивы ОС могут не содержать новых версий Python, а достаточно новые дистрибутивы — старых версий Python. В особых случаях репозиторий вообще может содержать только одну версию среды исполнения.

Сборка из исходного кода

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

А ещё сборка из исходного кода — это единственный вариант для тех, кто хочет что-то в этом самом коде изменить или скомпилировать интерпретатор для какой-то экзотической платформы (встраиваемые системы, ретро-железо).

pyenv

Ещё одним из способов получения разных версий среды исполнения на одной машине является pyenv. Это "менеджер версий", выполненный в стиле rbenv для Ruby, nvm для NodeJS и т.п.

Миссия pyenv — управлять установленными версиями Python и делать некую версию "активной". Активная версия вызывается, если мы выполняем команду python (а также pip ), при этом разные проекты могут использовать разные активные версии и даже более чем одну одновременно. Последнее свойство полезно авторам библиотек, рассчитанных на широкий круг пользователей — таковые всегда нужно тестировать на разных версиях Python.

Установить pyenv достаточно просто, ведь инструмент представляет собой набор shell scripts. Именно поэтому получился pyenv максимально кроссплатформенным. Но за эту кроссплатформенность приходится платить тем, что каждую версию среды исполнения нужно компилировать из исходного кода! Для компиляции того же CPython потребуется компилятор Си ( gcc на Linux и clang на MacOS), и заголовочные файлы для библиотек, которые использует интерпретатор. Полный список пререквизитов для сборки приходится гуглить.

Установка системным пакетным менеджером из сторонних источников

Для большинства Unix-like ОС, помимо официальных репозиториев, существуют и неофициальные источники пакетов.

Для Debian-like систем, таких как Ubuntu и её производные, сторонние источники пакетов называются PPA, Personal Package Archives. Подключить любой PPA достаточно просто, но нужно понимать, что вы таким образом соглашаетесь на установку пакетов из стороннего источника, никак не подчиняющегося авторам дистрибутива ОС! Подключайте только хорошо зарекомендовавшие себя PPA, например от самих авторов ПО, которое вы хотите установить!

Для Ubuntu-based систем существует PPA от команды «deadsnakes». Это проверенный источник пакетов с самыми разными версиями Python как для свежих релизов ОС, так и для релизов "второй свежести".

Главное преимущество установки пакетов из проверенных PPA состоит в том, что пакеты обычно содержат оптимизированные под конкретный дистрибутив сборки с должным количеством обновлений и исправлений. Такие сборки более безопасны и производительны, чем те, что собраны вручную из исходников.

К тому же в популярных PPA пакеты обновляются своевременно, чего нельзя сказать про пакеты для устаревших релизов ОС, для которых срок поддержки закончился. Конечно, такие релизы лучше вообще не использовать (небезопасно!), но иногда может не быть выбора, а с PPA вы хотя бы будете иметь свежие версии среды исполнения.

Псевдонимы python , python2 , python3

Исторически сложилось так, что интерпретатор Python запускается командой python . Но в какой-то момент случились Python3, обратная несовместимость, "разброд и шатания". Чтобы внести некоторую определённость, был представлен PEP-394: The "python" Command on Unix-Like Systems. Однако даже этот PEP разрешает разным системам самим выбирать, использовать ли Py2 и Py3 вместе или выбрать что-то одно. Системы должны лишь обеспечить, чтобы

  • команда python2 вызывала некую версию Python 2.x, если таковая вообще предоставляется;
  • команда python3 вызывала некую версию Python 3.x, если таковая предоставляется;
  • команда python соответствовала либо python2 , либо python3 (но не ссылалась на какую-то "третью" версию рантайма).

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

Такое "разнообразие" сильно усложняет жизнь разработчикам ПО, особенно — авторам инструментов разработки! Разработчик может написать скрипт для Py2 и указать в shebang #!/usr/bin/env python . Но на одних ОС команда python вообще не будет доступна и скрипт просто не запустится, а на других python будет означать какой-нибудь Python 3.8 и скрипт может даже запуститься, но сломается в процессе выполнения.

И даже если автор использует техники, позволяющие писать портируемый код (six, 3to2), умеющий выполняться и на Py2, и на Py3, всё равно непонятно что же указать в shebang!

Вышеупомянутый PEP советует

  • либо фиксировать версию явно (только Py2 или только Py3),
  • либо требовать использования виртуальных окружений (в ВО всегда будет доступна команда python )
  • либо не писать shebang руками, а вместо этого использовать средства setuptools или другой системы пакетирования, создающие точки входа в зависимости при установке пакета (у точек входа shebang будет правильный).

Установка poetry на системы с разными версиями Python

На момент написания статьи poetry (это такой менеджер виртуальных окружений, сборщик пакетов и проч — "швейцарский нож" разработчика на Python) страдал от проблем с версиями рантайма: при установке рекомендованными способом скрипт-установщик завершался с ошибкой, либо установка проходила успешно, но затем не работала сама программа.

Дело (было?) в том, что и в скрипте-установщике и в точках входа в программу в shebang прописан python ! Сама программа работает и на Py2, и на Py3, но авторы исходили из предположения, что на целевой системе в любом случае будет присутствовать псевдоним python , вызывающий тот или иной интерпретатор. На некоторых системах такой команды нет…

Если использовать pyenv, оный всегда предоставляет команду python и poetry "просто работает". Нет проблем и на старых дистрибутивах, где ещё не отказались окончательно от Py2 . И конечно всё работает в виртуальном окружении. Рассмотрим этот вариант поподробнее.

Установка в выделенное виртуальное окружение

Для начала нам понадобится само окружение. Предположим, что Python3 вы уже так или иначе поставили. Делаем раз

Программа установлена! Теперь создаём символическую ссылку на точку входа в папке, видимой в PATH , например, в $HOME/.local/bin :

Работает! Обновлять программу в будущем можно с помощью того же pip (который в окружении). А можно и вовсе автоматизировать процесс установки такого вот Python-софта с помощью pipx.

Особенности использования poetry, установленного в виртуальное окружение

Poetry построен так, чтобы работать с абстрактной версией python. Поэтому он хорошо сочетается с pyenv: один на себя берёт управление разными пайтонами, а другой — проектами на этих пайтонах.

Но эта привязка к команде python немного мешает, когда poetry установлен в своём собственном виртуальном окружении: в этом окружении Python уже известен и не может быть изменён. Данная особенность упомянута в документации к poetry, так что это "не баг, а фича". И всё же есть способ обойти сие ограничение: можно инициализировать окружение вручную с нужной версией Python и настроить poetry на использование этого готового окружения.

Для начала учим poetry создавать окружения не в своём кэше, а в папке с проектом:

С этих пор для каждого проекта виртуальное окружение будет располагаться в поддиректории .venv .

Уже в конкретном проекте инициализируем окружение командой

(для Py2 команда будет другой, т.к. модуль venv тогда ещё не поставлялся вместе со средой исполнения).

Теперь можно работать с poetry как обычно. Несмотря на то, что Python в проекте, возможно, отличается от рантайма, запускающего poetry!

How to Install Multiple Python Versions on your Computer and use them with VSCode

Why should you use pyenv and Virtual Python Environments?

As a programmer, either employed at a company, freelancer or even as a hobbyist, you usually work on multiple programming projects simultaneously. And most of those projects require different Python versions and depend on other modules like a particular version of numpy , for example. Or, if you created a Python module yourself and want to validate that it runs correctly on different Python versions, you need a way to install several Python versions on your system. And sometimes, you want to take a sneak at the latest Python release candidate but don’t want to ruin your production system.

For all those situations, pyenv and virtual environments ( venv ) offer an easy solution for installing different Python versions on your system and setting up environments with other requirements.

In this article and the accompanying Youtube videos, you learn how to install and set up pyenv and venv under Windows 10, macOS, and Ubuntu Linux and how to use it with VSCode.

Installing pyenv

Windows 10/11

pyenv actually started as a tool for Unix platforms such as Linux and macOS; however, there is an excellent Windows 10/11 port of it which can be found in this GitHub repository: https://github.com/pyenv-win/pyenv-win

Installing pyenv-win is not very straightforward due to how Windows 10/11 and PowerShell works, but if you follow those steps, it shouldn’t be too much of a hassle:

  1. Download pyenv-win ZIP-archive: pyenv-win
  2. Create a new folder .pyenv in your user folder with the name .pyenv . You can do this using the Explorer or the following PowerShell command:

And press A to choose Yes to ALL. Afterward, you can close this PowerShell window and open a new one without admin privileges. Set PowerShell execution policy

Run pyenv help in the PowerShellIf you encounter a security warning from where you have to choose if you want to run pyenv you can disable this warning by “unblocking” the pyenv script with the following command:

macOS

Before you can install pyenv on macOS, several other software packages have to be installed before. Firstly you need the XCode command line tools, which are installed via the following command:

As pyenv builds the Python versions from scratch, some libraries for the build process are required. Those libraries can be installed through the package manager Homebrew:

Installing pyenv on macOS can be done in two ways. The first one is to use the package manager Homebrew:

And after the installation has finished successfully, enter the following to add the pyenv to your $PATH and start pyenv when a new terminal window is opened (if you are not using zsh as a shell, you have to change

If you don’t want to install pyenv via Homebrew, you can install it directly from the GitHub repository. Enter the following command into your command line to clone the pyenv GitHub repository into your home directory:

After cloning it you need to enter the following commands to add pyenv to your $PATH and start it when a new terminal window is opened (if you use a different shell than zsh you have to change

Linux (Debian/Ubuntu)

To install pyenv on Debian or Ubuntu-based Linux distributions, you have to install several libraries and packages necessary for building Python from scratch. Enter the following command into your terminal to install all necessary packages:

To install pyenv you can clone it directly from the GitHub repository:

After cloning it you need to enter the following commands to add pyenv to your $PATH and start it when a new terminal is opened (if you use a different shell than bash you have to change

Using pyenv

After you successfully installed pyenv it is time to look at the different commands that pyenv offers to manage different Python versions.

Probably the most important command is:

With this command, you can install a specific Python version on your system. To see all versions that are available to install enter:

This will print out a very long list on your terminal (depending on your operating system) of Python versions you can install. And it is not just the standard CPython versions. There is also pypy , which is an implementation of Python in Python itself. Or anaconda , which is very popular in the sciences and data mining. Pick your preferred Python version and use pyenv install to install it on your system.

To see which versions you already installed on, enter the following command into your terminal:

This command will list all the Python versions that you can choose from pyenv . The version that is currently active has an asterisk ( * ) in front of it:

If you want to know which Python version is currently active in your shell, just type:

Now, after you installed several different versions, how do you set a specific version? To select a default Python version that is active when you open a new terminal, you use the global command:

Ensure to enter the exact name of the installed Python version shown when you enter pyenv versions . Alternatively to pyenv global [PYTHON_VERSION] , you can also set an environment variable (Unix only) PYENV_VERSION with:

If you want to set a specific Python version for your current terminal session, use:

This will set the Python version only as long as your session is active. So after you close your terminal, everything is back to default.

To set a project Python version that is active as soon as you “ cd ” into the project directory, enter the following when you are inside of the project’s root directory:

This will create the file .python-version that contains the [PYTHON_VERSION] . You can even check that by entering pyenv versions, and it will tell you based on what setting the currently active Python version was selected.

Of course, there are more pyenv commands, but I won’t go into those in this article. You can find a complete command reference over here: pyenv Command Reference.

Creating Virtual Environments

The real power of Python comes from its vast amount of modules ranging from graph theory to machine learning. To install those modules, the pip command is used. If you are using pyenv and you enter pip:

and for Windows PowerShell:

It will show you that pip is called from the .pyenv directory. And if you install a module using pip it is installed into your .pyenv directory tied to the currently active version. So if you install numpy while your current Python version is 3.9.6 numpy won’t be available when you switch to anaconda3-2021.05 . However, this granularity might not be enough, and you need a project-based distinction between different modules. And virtual environments do exactly that for you.

To create a new virtual environment for your project, open a terminal in your project’s root directory. Make sure you set your desired Python version for this project using pyenv local [PYTHON_VERSION] then enter:

This command will create a new directory .venv which includes the Python interpreter (provided by pyenv ) and all the modules installed using pip later on. After creating the newly created virtual environment, you have to activate it. This is done by entering:

and for Windows PowerShell:

Now a (.venv) string will appear in front of your command line. After you activate the virtual environment, you can check with which python or get-command python that is now called from the .venv directory. And when you use pip , it also installs all modules into the .venv directory. In the rare case you messed up your virtual environment, you can delete the .venv directory and create a new one with python -m venv .venv .

Using Virtual Environments with VSCode

Now that you successfully installed pyenv and set up virtual environments, I will show you in this section how to tell VSCode to activate virtual environments by default for your Python projects.

When you open your Python project directory with VSCode and create a virtual environment, it won’t activate it by default. To do this, you have to open the workspace settings.json with Ctrl+Shift+P or Cmd+Shift+P on macOS and enter settings.json.

Open Workspace settings.json

This will create a new file .vscode/settings.json in your project’s root directory. When you now run your Python application, it will automatically activate your virtual environment. In the newly created settings.json enter the new value

Activate Environment

And when you now run your Python program in VSCode it will automatically activate your virtual environment.

Run with virtual environment

Conclusion

I hope this article on how to set up pyenv and virtual Python environments and the related Youtube videos were helpful for you. If you got any questions regarding the setup process, leave me a comment under my Youtube videos or join our lovely Discord community.

Управление несколькими версиями Python под управлением Ubuntu 20.04

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

Ubuntu 20.04 это первая LTS версия Ubuntu в которой отсутствует Python2 и которая поставляется из коробки с установленной версией Python 3.8.5. Но что если написанное вами приложение использующее более новую версию Python? Если вы, как и я, пытались заменить установленную по умолчанию в системе версию, то в процессе сломали вашу ОС. Если до этого вам никто не говорил не делать этого, тогда я возьму на себя эту честь: не делайте этого.

Итак, что же нам делать? Существует нескольок путей как обновить версию Python на Ubuntu, но использование вастроенного в Ubuntu’s механизма «alternative install» оптимально по нескольким причинам:

Мы хотим оставить нетронутойси стемную версию Python

По возможности не возиться с Python PATH

Мы можем удобно переключать активную версию Python с использованием CLI

Мы пройдемся по способу легкой и безопасной установки последней версии Python не затрагивая системную версию Python.

Скачивание последней версии Python

Первый шаг должен быть вам знаком: нам необходимо обновить зеркала Ubuntu и установленные пакеты, что бы быть уверенными что мы загружаем последние версии пакетов при установке чего-либо:

Установка другой версии Python на Ubuntu трубует установки целого ряда зависимых библиотек для Python. Я честно гвооря не уверен что делает половина из этого, и скорее всего это никому из нас никогда не понадобится. Но поверьте, это необходимый шаг:

Именно здесь многие могут начать установку Python с помощью Ubuntu package manager командой apt-get install python3.X. Мы скачаем и соберем последнюю версию Python из исходные кодов по нескольким причинам. Если версия Python достаточно свежая, некоторые машины под управлением Ubuntu могут не иметь обновленных зеркал что бы получить последнюю версию, но важнее всего то, что этот способ позволяет упростить управление несколькими версиями Python на Ubuntu.

Последнюю версию Python всегда можно найти на официальной странице с релизами на Python.org:

Первая ссылка на указанной странице должна называться Latest Python 3 Release — Python 3.X. Перейдя по ней необходимо прокрутить вниз страницы до секции «Files» и скопировать URL ссылки Gzipped source tarball.

На вашей Ubuntu машине необходимо теперь скачать эти исходные коды с помощью утилиты «wget». Ниже пример команд для скачивания заархивированной версии Python 3.9.2 в папку /opt и распаковка ее:

Теперь последняя версия Python скачана. После этого нам остается ее установить… правильно.

Установка альтернативной версии Python из исходных кодов

Главное разочарование установки Python с использованием команды apt-get install python3.X это что Python будет установлен нормально, но Ubuntu будет по прежнему использовать установленную в системе по умолчанию версию Python. К счастью для нас Ubuntu позволяет устанавливать нам дополнительные (альтернативные) версии Python с использованием команды make altinstall :

Исполнение этих команд может занять некоторое время. После того, как команды будут выполнены вы можете увидеть python3.9 в вашей директории /usr/local/bin/ :

Итак, теперь у нас есть две установленные версии Python: установленная в системе по-умолчанию Python 3.8.5 и добавленная нами новая версия Python 3.9.2. Мы хотим оставить нетронутой установленную в системе версию по-умолчанию, но мы так же хотим запускать написанные нами приложения в версии Python 3.9… итак как мы можем этим управлять?

Linux предусматривает такой сценарий с помощью команды update-alternatives . Мы можем сказать Ubuntu что у нас есть ветка с альтернативной версией на нашей машине, это предоставит нам возможность легко переключаться между ними. Вот как это работает:

Мы запускаем update-alternatives дважды: один раз для Python 3.8, и один раз для Python 3.9. Теперь мы можем использовать команду update-alternatives —list что бы посмотреть все альтернативные версии какого-либо установленного ПО:

Теперь мы можем переключаться между установленными версиями Python! Запустите следующую команду:

После выполнения команды вы должны получить подсказку как в приведенном ниже примере. Это будет список всех доступных версий Python в вашей системе. Выберите версию которую хотите использовать введя соответствующий номер версии указанный в колонке Selection :

И вы это сделали! Для переключения версии Python все что нужно — это ввести запрошенный номер версии Python указанный в колонке selection .

Это прозвучит абсурдно, но изменить версию Python в Ubuntu ничего не сломав — это впечатляет. Я бы сказал что это в основном вина тех, кто преподаает Python. Если «учат те, кто не может сделать», то было бы логично предположить что Python преподают те, кто не запустил ни одного значимого проекта. Это было жестко, но не бейте меня нисмотря ни на что.

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

Вы наверняка заметили что Ubuntu 20.04 (и новее) заставляют нас явно указывать python3 при использовании Python несмотря на отсутствие Python 2 на машине. Это немного раздражает, но так же потенциально может сломать библиотеки которые пытаются использовать Python (NPM, sqlite и node-qyp например)

Возможно вы чувствуетет в себе достаточно сил что бы создать alias, который будет при обращении к python ссылаться на python3, но к сожалению это не будет работать так, как вам бы хотелось. Хорошая новость в том, что есть простое решение:

Да, есть целый пакет для Ubuntu созданный специально для решения этой задачи. Но это работает ¯_(ツ)_/¯.

Managing Multiple Python Versions With pyenv

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Start Managing Multiple Python Versions With pyenv

Have you ever wanted to contribute to a project that supports multiple versions of Python but aren’t sure how you would easily test all the versions? Are you ever curious about the latest and greatest versions of Python? Maybe you’d like to try out these new features, but you don’t want to worry about messing up your development environment. Luckily, managing multiple versions of Python doesn’t have to be confusing if you use pyenv .

This article will provide you with a great overview of how to maximize your time spent working on projects and minimize the time spent in headaches trying to use the right version of Python.

In this article, you’ll learn how to:

  1. Install multiple versions of Python
  2. Install the latest development version of Python
  3. Switch between the installed versions
  4. Use virtual environments with pyenv
  5. Activate different Python versions and virtual environments automatically

Free Download: Get a sample chapter from Python Tricks: The Book that shows you Python’s best practices with simple examples you can apply instantly to write more beautiful + Pythonic code.

Why Use pyenv ?

pyenv is a wonderful tool for managing multiple Python versions. Even if you already have Python installed on your system, it is worth having pyenv installed so that you can easily try out new language features or help contribute to a project that is on a different version of Python. Using pyenv is also a great way to install pre-release versions of Python so that you can test them for bugs.

Why Not Use System Python?

“System Python” is the Python that comes installed on your operating system. If you’re on Mac or Linux, then by default, when you type python in your terminal, you get a nice Python REPL.

So, why not use it? One way to look at it is that this Python really belongs to the operating system. After all, it came installed with the operating system. That’s even reflected when you run which :

Here, python is available to all users as evidenced by its location /usr/bin/python . Chances are, this isn’t the version of Python you want either:

To install a package into your system Python, you have to run sudo pip install . That’s because you’re installing the Python package globally, which is a real problem if another user comes along and wants to install a slightly older version of the package.

Problems with multiple versions of the same package tend to creep up on you and bite you when you least expect it. One common way this problem presents itself is a popular and stable package suddenly misbehaving on your system. After hours of troubleshooting and Googling, you may find that you’ve installed the wrong version of a dependency, and it’s ruining your day.

Even if your Python version is installed in /usr/local/bin/python3 , you’re still not safe. You will run into the same permissions and flexibility problems described above.

In addition, you don’t really have much control over what version of Python comes installed on your OS. If you want to use the latest features in Python, and you’re on Ubuntu for example, you might just be out of luck. The default versions might be too old, which means you’ll just have to wait for a new OS to come out.

Finally, some operating systems actually use the packaged Python for operation. Take yum for example, which makes heavy use of Python to do its job. If you install a new version of Python and aren’t careful to install it into your user space, you could seriously damage your ability to use your OS.

What About a Package Manager?

The next logical place to look is package managers. Programs such as apt , yum , brew , or port are typical next options. After all, this is how you install most packages to your system. Unfortunately, you’ll find some of the same problems using a package manager.

By default, package managers tend to install their packages into the global system space instead of the user space. Again, these system level packages pollute your development environment and make it hard to share a workspace with others.

Once again, you still don’t have control over what version of Python you can install. It’s true some repositories give you a greater selection, but by default, you’re looking at whatever version of Python your particular vendor is up to on any given day.

Even if you do install Python from a package manager, consider what would happen if you’re writing a package and want to support and test on Python 3.4 — 3.7.

What would happen on your system when you type python3 ? How would you switch quickly between the different versions? You can certainly do it, but it is tedious and prone to error. Nevermind the fact that if you want PyPy, Jython, or Miniconda, then you’re probably just out of luck with your package manager.

With these constraints in mind, let’s recap the criteria that would let you install and manage Python versions easily and flexibly:

  1. Install Python in your user space
  2. Install multiple versions of Python
  3. Specify the exact Python version you want
  4. Switch between the installed versions

pyenv lets you do all of these things and more.

Installing pyenv

Before you install pyenv itself, you’re going to need some OS-specific dependencies. These dependencies are mostly development utilities written in C and are required because pyenv installs Python by building from source. For a more detailed breakdown and explanation of the build dependencies, you can check out the official docs. In this tutorial, you’ll see the most common ways to install these dependencies.

Note: pyenv did not originally support Windows. However, there appears to be some basic support with the pyenv-win project that recently became active. If you use Windows, feel free to check it out.

Build Dependencies

pyenv builds Python from source, which means you’ll need build dependencies to actually use pyenv . The build dependencies vary by platform. If you are on Ubuntu/Debian and want to install the build dependencies, you could use the following:

This uses Apt to install all the build dependencies. Let this run, and you’ll be ready to go for Debian systems.

If you use Fedora/CentOS/RHEL, you could use yum to install your build dependencies:

This command will install all the build dependencies for Python using yum .

macOS users can use the following command:

This command relies on Homebrew and installs the few dependencies for macOS users.

Tip: When running Mojave or higher (10.14+) you will also need to install the additional SDK headers:

Thanks to Rodrigo Viera for the update.

If you’re instead using openSUSE then you would run the following:

Once again, this command installs all the Python build dependencies for your system.

Finally, for Alpine users, you can use this:

This command uses apk as the package manager and will install all build dependencies for Python on Alpine.

Using the pyenv-installer

After you’ve installed the build dependencies, you’re ready to install pyenv itself. I recommend using the pyenv-installer project:

This will install pyenv along with a few plugins that are useful:

  1. pyenv : The actual pyenv application
  2. pyenv-virtualenv : Plugin for pyenv and virtual environments
  3. pyenv-update : Plugin for updating pyenv
  4. pyenv-doctor : Plugin to verify that pyenv and build dependencies are installed
  5. pyenv-which-ext : Plugin to automatically lookup system commands

Note: The above command is the same as downloading the pyenv-installer script and running it locally. So if you’d like to see exactly what you’re running, you can view the file yourself. Alternatively, if you really don’t want to run a script, you can checkout the manual installation instructions.

At the end of the run, you should see something like this:

The output will be based on your shell. But you should follow the instructions to add pyenv to your path and to initialize pyenv / pyenv-virtualenv auto completion. Once you’ve done this, you need to reload your shell:

That’s it. You now have pyenv and four useful plugins installed.

Using pyenv to Install Python

Now that you have pyenv installed, installing Python is the next step. You have many versions of Python to choose from. If you wanted to see all the available CPython 3.6 through 3.8, you can do this:

The above shows all the Python versions that pyenv knows about that match the regular expression. In this case, that is all available CPython versions 3.6 through 3.8. Likewise, if you wanted to see all the Jython versions, you could do this:

Again, you can see all the Jython versions that pyenv has to offer. If you want to see all the versions, you can do the following:

Once you find the version you want, you can install it with a single command:

Having Problems? The pyenv documentation has great installation notes as well as a useful FAQ along with common build problems.

This will take a while because pyenv is building Python from source, but once it’s done, you’ll have Python 3.7.2 available on your local machine. If you don’t want to see all the output, just remove the -v flag. Even development versions of CPython can be installed:

Pro Tip: If you’ve been using pyenv for a while and don’t see the version you’re looking for, you may need to run pyenv update to update the tool and make sure you have access to the latest versions.

For the rest of the tutorial, the examples assume you’ve installed 3.6.8 and 2.7.15 , but you’re free to substitute these values for the Python versions you actually installed. Also note that the system Python version in the examples is 2.7.12 .

Installation Location

As mentioned before, pyenv works by building Python from source. Each version that you have installed is located nicely in your pyenv root directory:

All of your versions will be located here. This is handy because removing these versions is trivial:

Of course pyenv also provides a command to uninstall a particular Python version:

Using Your New Python

Now that you’ve installed a couple of different Python versions, let’s see some basics on how to use them. First, check what versions of Python you have available:

The * indicates that the system Python version is active currently. You’ll also notice that this is set by a file in your root pyenv directory. This means that, by default, you are still using your system Python:

If you try to confirm this using which , you’ll see this:

This might be surprising, but this is how pyenv works. pyenv inserts itself into your PATH and from your OS’s perspective is the executable that is getting called. If you want to see the actual path, you can run the following:

If, for example, you wanted to use version 2.7.15, then you can use the global command:

Pro Tip: A great way to get peace of mind that the version of Python you just installed is working properly is to run the built-in test suite:

This will kick off lots of internal Python tests that will verify your installation. You can just kick back and watch the tests pass.

If you ever want to go back to the system version of Python as the default, you can run this:

You can now switch between different versions of Python with ease. This is just the beginning. If you have many versions that you want to switch between, typing these commands consistently is tedious. This section goes over the basics, but a better workflow is described in working with multiple environments.

Exploring pyenv Commands

pyenv offers many commands. You can see a complete list of all available commands with this:

This outputs all command names. Each command has a —help flag that will give you more detailed information. For example, if you wanted to see more information on the shims command you could run the following:

The help message describes what the command is used for and any options you can use in conjunction with the command. In the following sections, you’ll find a quick, high-level overview of the most used commands.

install

You’ve already seen the install command above. This command can be used to install a specific version of Python. For example, if you wanted to install 3.6.8 you would use this:

The output shows us pyenv downloading and installing Python. Some of the common flags you may want to use are the following:

Flag Description
-l/—list Lists all available Python versions for installation
-g/—debug Builds a debug version of Python
-v/—verbose Verbose mode: print compilation status to stdout

versions

The versions command displays all currently installed Python versions:

This output shows not only that 2.7.15 , 3.6.8 , 3.8-dev , and your system Python are installed, but also shows you that the system Python is active. If you only care about the current active version, you can use the following command:

This command is similar to versions but only shows you the current active Python version.

which

The which command is helpful for determining the full path to a system executable. Because pyenv works by using shims, this command allows you to see the full path to the executable pyenv is running. For example, if you wanted to see where pip is installed, you could run this:

The output displays the full system path for pip . This can be helpful when you’ve installed command-line applications.

global

The global command sets the global Python version. This can be overridden with other commands, but is useful for ensuring you use a particular Python version by default. If you wanted to use 3.6.8 by default, then you could run this:

This command sets the

/.pyenv/version to 3.6.8 . For more information, see the section on specifying your Python version.

local

The local command is often used to set an application-specific Python version. You could use it to set the version to 2.7.15 :

This command creates a .python-version file in your current directory. If you have pyenv active in your environment, this file will automatically activate this version for you.

shell

The shell command is used to set a shell-specific Python version. For example, if you wanted to test out the 3.8-dev version of Python, you can do this:

This command activates the version specified by setting the PYENV_VERSION environment variable. This command overwrites any applications or global settings you may have. If you want to deactivate the version, you can use the —unset flag.

Specifying Your Python Version

One of the more confusing parts of pyenv is how exactly the python command gets resolved and what commands can be used to modify it. As mentioned in the commands, there are 3 ways to modify which version of python you’re using. So how do all these commands interact with one another? The resolution order looks a little something like this:

Pyenv pyramid for order of resolution

This pyramid is meant to be read from top to bottom. The first of these options that pyenv can find is the option it will use. Let’s see a quick example:

Here, your system Python is being used as denoted by the * . To exercise the next most global setting, you use global :

You can see that now pyenv wants to use 3.6.8 as our Python version. It even indicates the location of the file it found. That file does indeed exist, and you can list its contents:

Now, let’s create a .python-version file with local :

Here again, pyenv indicates how it would resolve our python command. This time it comes from

/.python-version . Note that the searching for .python-version is recursive:

Even though there isn’t a .python-version in subdirectory , the version is still set to 2.7.15 because .python-version exists in a parent directory.

Finally, you can set the Python version with shell :

All this did is set the $PYENV_VERSION environment variable:

If you’re feeling overwhelmed by the options, the section on working with multiple environments goes over an opinionated process for managing these files, mostly using local .

Virtual Environments and pyenv

Virtual environments are a big part of managing Python installations and applications. If you haven’t heard of virtual environments before, you can check out Python Virtual Environments: A Primer.

Virtual environments and pyenv are a match made in heaven. pyenv has a wonderful plugin called pyenv-virtualenv that makes working with multiple Python version and multiple virtual environments a breeze. If you’re wondering what the difference is between pyenv , pyenv-virtualenv , and tools like virtualenv or venv , then don’t worry. You’re not alone.

Here’s what you need to know:

  • pyenv manages multiple versions of Python itself.
  • virtualenv/venv manages virtual environments for a specific Python version.
  • pyenv-virtualenv manages virtual environments for across varying versions of Python.

If you’re a die-hard virtualenv or venv user, don’t worry: pyenv plays nicely with either. In fact, you can keep the same workflow you’ve had if you’d prefer, though I think pyenv-virtualenv makes for a nicer experience when you’re switching between multiple environments that require different Python versions.

The good news is that since you used the pyenv-installer script to install pyenv , you already have pyenv-virtualenv installed and ready to go.

Creating Virtual Environments

Creating a virtual environment is a single command:

Technically, the <python_version> is optional, but you should consider always specifying it so that you’re certain of what Python version you’re using.

The <environment_name> is just a name for you to help keep your environments separate. A good practice is to name your environments the same name as your project. For example, if you were working on myproject and wanted to develop against Python 3.6.8, you would run this:

The output includes messages that show a couple of extra Python packages getting installed, namely wheel , pip , and setuptools . This is strictly for convenience and just sets up a more full featured environment for each of your virtual environments.

Activating Your Versions

Now that you’ve created your virtual environment, using it is the next step. Normally, you should activate your environments by running the following:

You’ve seen the pyenv local command before, but this time, instead of specifying a Python version, you specify an environment. This creates a .python-version file in your current working directory and because you ran eval «$(pyenv virtualenv-init -)» in your environment, the environment will automatically be activated.

You can verify this by running the following:

You can see a new version has been created called myproject and the python executable is pointing to that version. If you look at any executable this environment provides, you will see the same thing. Take, for example, pip :

If you did not configure eval «$(pyenv virtualenv-init -)» to run in your shell, you can manually activate/deactivate your Python versions with this:

The above is what pyenv-virtualenv is doing when it enters or exits a directory with a .python-version file in it.

Working With Multiple Environments

Putting everything you’ve learned together, you can work effectively with multiple environments. Let’s assume you have the following versions installed:

Now you want to work on two different, aptly named, projects:

  1. project1 supports Python 2.7 and 3.6.
  2. project2 supports Python 3.6 and experiments with 3.8-dev.

You can see that, by default, you are using the system Python, which is indicated by the * in the pyenv versions output. First, create a virtual environment for the first project:

Finally, notice that when you cd out of the directory, you default back to the system Python:

You can follow the above steps and create a virtual environment for project2:

These are one time steps for your projects. Now, as you cd between the projects, your environments will automatically activate:

No more remembering to activate environments: you can switch between all your projects, and pyenv will take care of automatically activating the correct Python versions and the correct virtual environments.

Activating Multiple Versions Simultaneously

As described in the example above, project2 uses experimental features in 3.8. Suppose you wanted to ensure that your code still works on Python 3.6. If you try running python3.6 , you’ll get this:

pyenv informs you that, while Python 3.6 is not available in the current active environment, it is available in other environments. pyenv gives you a way to activate multiple environments at once using a familiar command:

This indicates to pyenv that you would like to use the virtual environment project2 as the first option. So if a command, for example python , can be resolved in both environments, it will pick project2 before 3.6.8 . Let’s see what happens if you run this:

Here, pyenv attempts to find the python3.6 command, and because it finds it in an environment that is active, it allows the command to execute. This is extremely useful for tools like tox that require multiple versions of Python to be available on your PATH in order to execute.

Pro Tip: If you’re using tox and pyenv , you should checkout the tox-pyenv package.

Suppose that in the above example, you’ve found a compatibility problem with your library and would like to do some local testing. The testing requires that you install all the dependencies. You should follow the steps to create a new environment:

Once you’re satisfied with your local testing, you can easily switch back to your default environment:

Conclusion

You can now more easily contribute to a project that wants to support multiple environments. You can also more easily test out the latest and greatest Python versions without having to worry about messing up your development machine, all with a wonderful tool: pyenv .

You’ve seen how pyenv can help you:

  • Install multiple versions of Python
  • Switch between the installed versions
  • Use virtual environments with pyenv
  • Activate different Python versions and virtual environments automatically

If you still have questions, feel free to reach out either in the comments section or on Twitter. Additionally, the pyenv documentation is a great resource.

Bonus: Displaying Your Environment Name in Your Command Prompt

If you’re like me and constantly switching between various virtual environments and Python versions, it’s easy to get confused about which version is currently active. I use oh-my-zsh and the agnoster theme, which by default makes my prompt look like this:

Agnoster theme with no pyenv prompt

At a glance, I don’t know which Python version is active. To figure it out, I would have to run python -V or pyenv version . To help reduce my time spent on figuring out my active Python environment, I add the pyenv virtual environment I’m using to my prompt:

Environment name being shown in ZSH command prompt

My Python version in this case is project1-venv and is displayed immediately at the beginning of the prompt. This allows me to quickly see what version of Python I’m using right away. If you’d like to use this too, you can use my agnoster-pyenv theme.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Start Managing Multiple Python Versions With pyenv

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Logan Jones

Hi, I'm Logan, an open source contributor, writer for Real Python, software developer, and always trying to get better. Feel free to reach out and let's get better together!

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Brad Solomon

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Master Real-World Python Skills
With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal. Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

Читать:
Папка установки стим настроена только для чтения что делать

Похожие статьи