- Switching between Python 2 and 3 versions on Ubuntu 20.04
- Installing Python 2 in Ubuntu 20.04 LTS
- How to switch between Python 2 and 3 versions on Ubuntu 20.04
- Method 1: My recommended way by configuring
- Method 2: Old-school way without configuration
- Conclusion
- 2. Using Python on Unix platformsВ¶
- 2.1. Getting and installing the latest version of PythonВ¶
- 2.1.1. On LinuxВ¶
- 2.1.2. On FreeBSD and OpenBSDВ¶
- 2.1.3. On OpenSolarisВ¶
- 2.2. Building PythonВ¶
- 2.3. Python-related paths and filesВ¶
- 2.4. MiscellaneousВ¶
- 2.5. Custom OpenSSLВ¶
- Installing Python 3 on Linux¶
- Working with Python 3¶
- Setuptools & Pip¶
- Pipenv & Virtual Environments¶
- O’Reilly Book
- Несколько версий Python на Linux-машине
- Использование нескольких версий Python на unix-подобных операционных системах.
- Что и зачем?
- Установка Python из репозиториев пакетов операционной системы.
- Сборка из исходного кода.
- pyenv
- Установка системным пакетным менеджером из сторонних источников.
- Псевдонимы python , python2 , python3 .
- Установка poetry на системы с разными версиями Python
- Установка в выделенное виртуальное окружение
Switching between Python 2 and 3 versions on Ubuntu 20.04
Are you missing Python 2 on your Ubuntu 20.04 system? It was dropped out completely since this Focal Fossa release, but here is how to install it and switch between version 2 and version 3 on your current Ubuntu installation.
I n the recent past, there has been a bit of debate on which Python version should one learn. Python 2 or Python 3. It’s now 2020 and pretty evident that Python 3 is the way to go. However, Python 2 is still in the market, and some people, including me, still use it in development. It brings forth the necessity of how we set up and switch between the two versions on your Linux system.
Ubuntu 18.04 LTS release came with several changes, and one is that Python 2 was no longer the default Python version in the system. Welcome, Ubuntu 20.04 LTS release; canonical dropped Python 2 entirely and no longer included it among the installation packages.
See the image below. When we try to execute the Python 2 command, which is by default “python,” we get “command not found” error.
Python 2 not packaged in Ubuntu 20.04
In this post, we will show you how to:
- Install Python 2 in Ubuntu 20.04 LTS
- Switch between Python 3 and Python 2 versions
Installing Python 2 in Ubuntu 20.04 LTS
Step 1) Launch the Terminal and type any of the commands below. You will be required to enter your root password.
Install Python2 in Ubuntu 20.04 LTS
Step 2) Once the installation complete, you can check the Python 2 version using the “–version” command.
Check the python version installed
From the image above, we can see we are running Python 2.7 and Python 3.8. Now, let’s jump on to one of the important parts of this tutorial of how to configure Python and switch between the two versions – Python 2 and Python 3.
How to switch between Python 2 and 3 versions on Ubuntu 20.04
Method 1: My recommended way by configuring
Step 1) Check all the available Python versions in your system. To do so, we will need to check the /bin directory. That is because we can have variations in Python 3. Say Python 3.7 and Python 3.8. In such situations, the –version command won’t be useful as it only lists the currently configured version.
Execute the commands below on the Terminal.
Check all the installed Python versions in the bin directory
Step 2) Once we have listed all the versions present on the system, we need to check whether there are any Python-alternatives configured.
Execute the command below on the Terminal.
Check for any Python alternatives configured on the system
From the image above, we see that there are no Python alternatives configured.
Step 3) Now, we will configure two Python alternatives. From the image in Step 2 above, we saw that I have Python 2.7 and Python 3.8 present on my system.
Execute the commands below on the Terminal.
Configure Python Alternatives
Step 4) We need to confirm the Python alternatives set and whether they are in use.
Execute the command below again.
Confirm the Python Alternatives set
On the prompt that appears on the Terminal, enter 1 or 2 to make your selection. In this post, we want to use Python 2; therefore, we will enter option 1.
Step 5) Now, let’s check the Python version currently running on our system. Execute the command below.
Check the currently running Python Version
To switch to another Python version, all you need to do is execute the command on Step 4 and select the other option. In this case, we would choose option 2 to use Python 3.
Method 2: Old-school way without configuration
This other method, we would refer to it as the manual way since we won’t perform any configurations. Follow the procedure below.
Step 1) Install Python 2 with the command below.
Step 2) Check the Python versions present in your system by running the command below.
Check all the installed Python versions in the bin directory
Step 3) In this post, we currently have Python 2 and Python 3 available. Now write your Python 2 or Python 3 code.
For example, below is a Python 2 code to print the sentence “Hello, This Fosslinux.com.“
Python2 Code
Step 4) To execute your code using Python 2, you will need to specify the version manually. For example, the python file is called Example.py. Execute the command below.
Execute the Python 2 code
If we used Python 3 to execute the code below, we would get an error, as shown below.
Error when using Python3 to execute Python2 code
If we were writing code using Python 3, we would specify Python 3 when running the program.
Conclusion
Despite Python 2 being dropped in the recent Linux releases, some people still find it advantageous and use it in their development. There are vast applications built using Python 2, and the transition to Python 3 has not been put into effect fully.
These and many other reasons make Python 2 still relevant in the development community. With the methods described above, you will be able to switch from one Python version to another easily when coding.
Источник
2. Using Python on Unix platformsВ¶
2.1. Getting and installing the latest version of PythonВ¶
2.1.1. On LinuxВ¶
Python comes preinstalled on most Linux distributions, and is available as a package on all others. However there are certain features you might want to use that are not available on your distro’s package. You can easily compile the latest version of Python from source.
In the event that Python doesn’t come preinstalled and isn’t in the repositories as well, you can easily make packages for your own distro. Have a look at the following links:
for Debian users
for OpenSuse users
for Fedora users
for Slackware users
2.1.2. On FreeBSD and OpenBSDВ¶
FreeBSD users, to add the package use:
OpenBSD users, to add the package use:
For example i386 users get the 2.5.1 version of Python using:
2.1.3. On OpenSolarisВ¶
You can get Python from OpenCSW. Various versions of Python are available and can be installed with e.g. pkgutil -i python27 .
2.2. Building PythonВ¶
If you want to compile CPython yourself, first thing you should do is get the source. You can download either the latest release’s source or just grab a fresh clone. (If you want to contribute patches, you will need a clone.)
The build process consists of the usual commands:
Configuration options and caveats for specific Unix platforms are extensively documented in the README.rst file in the root of the Python source tree.
make install can overwrite or masquerade the python3 binary. make altinstall is therefore recommended instead of make install since it only installs exec_prefix /bin/python version .
2.3. Python-related paths and filesВ¶
These are subject to difference depending on local installation conventions; prefix ( $
For example, on most Linux systems, the default for both is /usr .
Recommended location of the interpreter.
prefix /lib/python version , exec_prefix /lib/python version
Recommended locations of the directories containing the standard modules.
prefix /include/python version , exec_prefix /include/python version
Recommended locations of the directories containing the include files needed for developing Python extensions and embedding the interpreter.
2.4. MiscellaneousВ¶
To easily use Python scripts on Unix, you need to make them executable, e.g. with
and put an appropriate Shebang line at the top of the script. A good choice is usually
which searches for the Python interpreter in the whole PATH . However, some Unices may not have the env command, so you may need to hardcode /usr/bin/python3 as the interpreter path.
To use shell commands in your Python scripts, look at the subprocess module.
2.5. Custom OpenSSLВ¶
To use your vendor’s OpenSSL configuration and system trust store, locate the directory with openssl.cnf file or symlink in /etc . On most distribution the file is either in /etc/ssl or /etc/pki/tls . The directory should also contain a cert.pem file and/or a certs directory.
Download, build, and install OpenSSL. Make sure you use install_sw and not install . The install_sw target does not override openssl.cnf .
Build Python with custom OpenSSL (see the configure –with-openssl and –with-openssl-rpath options)
Patch releases of OpenSSL have a backwards compatible ABI. You don’t need to recompile Python to update OpenSSL. It’s sufficient to replace the custom OpenSSL installation with a newer version.
Источник
Installing Python 3 on Linux¶
This document describes how to install Python 3.6 or 3.8 on Ubuntu Linux machines.
To see which version of Python 3 you have installed, open a command prompt and run
If you are using Ubuntu 16.10 or newer, then you can easily install Python 3.6 with the following commands:
If you’re using another version of Ubuntu (e.g. the latest LTS release) or you want to use a more current Python, we recommend using the deadsnakes PPA to install Python 3.8:
If you are using other Linux distribution, chances are you already have Python 3 pre-installed as well. If not, use your distribution’s package manager. For example on Fedora, you would use dnf :
Note that if the version of the python3 package is not recent enough for you, there may be ways of installing more recent versions as well, depending on you distribution. For example installing the python3.9 package on Fedora 32 to get Python 3.9. If you are a Fedora user, you might want to read about multiple Python versions available in Fedora.
Working with Python 3¶
At this point, you may have system Python 2.7 available as well.
This might launch the Python 2 interpreter.
This will always launch the Python 3 interpreter.
Setuptools & Pip¶
The two most crucial third-party Python packages are setuptools and pip.
Once installed, you can download, install and uninstall any compliant Python software product with a single command. It also enables you to add this network installation capability to your own Python software with very little work.
Python 2.7.9 and later (on the python2 series), and Python 3.4 and later include pip by default.
To see if pip is installed, open a command prompt and run
To install pip, follow the official pip installation guide — this will automatically install the latest version of setuptools.
Note that on some Linux distributions including Ubuntu and Fedora the pip command is meant for Python 2, while the pip3 command is meant for Python 3.
However, when using virtual environments (described below), you don’t need to care about that.
Pipenv & Virtual Environments¶
The next step is to install Pipenv, so you can install dependencies and manage virtual environments.
A Virtual Environment is a tool to keep the dependencies required by different projects in separate places, by creating virtual Python environments for them. It solves the “Project X depends on version 1.x but, Project Y needs 4.x” dilemma, and keeps your global site-packages directory clean and manageable.
For example, you can work on a project which requires Django 1.10 while also maintaining a project which requires Django 1.8.
This page is a remixed version of another guide, which is available under the same license.
This opinionated guide exists to provide both novice and expert Python developers a best practice handbook to the installation, configuration, and usage of Python on a daily basis.
O’Reilly Book
This guide is now available in tangible book form!
All proceeds are being directly donated to the DjangoGirls organization.
Источник
Несколько версий Python на Linux-машине
Использование нескольких версий 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 вы уже так или иначе поставили. Делаем раз
Источник