- Как установить определенную версию Python в Ubuntu — Linux Hint
- Python в Ubuntu
- Установка конкретной версии Python
- Почему вам следует установить Python 3.5 или новее
- Вывод
- How to install a specific Python version on Ubuntu
- Python on Ubuntu
- Installing a specific version of Python
- Why you should install Python 3.5 or later
- Conclusion
Как установить определенную версию Python в Ubuntu — Linux Hint
Часто бывает так, что мы устанавливаем программу в нашу систему, и оказывается, что это неправильная версия. Это может привести к проблемам с совместимостью и производительностью, поскольку он может некорректно взаимодействовать со сторонними модулями. То же самое и с Python, и, как бдительные программисты, мы должны найти правильную версию, которая нам нужна. Поэтому в этом руководстве мы покажем вам, как установить определенную версию Python в вашей системе Ubuntu.
Python в Ubuntu
Обычно Python предустановлен во многих дистрибутивах Linux. В нашем случае это Python3. Начните новый сеанс Терминала через меню Действия или нажав Ctrl + Alt + T на клавиатуре. На всякий случай вы можете проверить, установлен ли в вашем дистрибутиве Python, выполнив следующую команду.
Или, если вы, как и мы, используете Python 3, приведенная ниже команда должна выполнить свою работу.
На изображении видно, что в системе работает Python 3.8.5. Рекомендуется обновить вашу версию Python, если вы используете Python 3.3 или ниже. Не торопитесь, чтобы узнать больше о том, какую версию вам следует получить, поскольку мы обсудим это в последнем сегменте статьи.
В разделах ниже мы продемонстрируем, как вы можете установить любую версию Python в вашей системе, будь то обновленная или устаревшая.
Установка конкретной версии Python
Первым шагом к установке Python является установка необходимых зависимостей и пакетов, необходимых для его установки. Однако для установки этих зависимостей у вас должен быть включен репозиторий multiverse. Вы можете включить его, выполнив приведенную ниже команду.
$ sudo apt-add-repository multiverse
Как только это будет решено, мы перейдем к установке первой зависимости. Выполните команду ниже, чтобы продолжить.
$ sudo apt-get install build-essential checkinstall
Он должен завершить загрузку и установку через несколько секунд. Как только это будет сделано, перейдите к следующему, выполнив команду ниже.
$ sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
Это длинная и сложная команда, поэтому просто скопируйте и вставьте ее в свой терминал, чтобы избежать ошибок при вводе.
Сделав это, мы переходим к загрузке Python и его установке. Чтобы показать вам, как установить конкретную версию, мы понизим наш Python с 3.8.5 до Python 2.7.
Сначала мы меняем текущий каталог на папку Downloads, в которую мы хотим загрузить пакет. Это можно сделать, выполнив команду ниже.
Следующим шагом является получение пакета с веб-сайта Python.
Нажмите здесь чтобы получить доступ к расположению, из которого вы можете выбрать любую версию Python по своему вкусу. Все, что нужно изменить в команде wget, — это ссылка.
После успешной загрузки определенной версии Python последние шаги просты и легки. Сначала мы извлечем пакет с помощью приведенной ниже команды.
Вы можете заменить номер версии на Python-версия.tgz согласно вашему пакету.
Следующие шаги включают открытие каталога Python, настройку файлов и его установку. Выполните приведенные ниже команды в указанном порядке, чтобы продолжить.
$ cd Python-2.7.12
$ ./configure
$ make
$ sudo checkinstall
Процесс установки, несмотря на то, что он простой и понятный, должен занять несколько минут. Как только это будет сделано, вы можете проверить, была ли установка успешной, просто выполнив команды, упомянутые в начале.
Как видно из изображения, мы успешно перешли с Python 3.8.5 на Python 2.7.12. Вы можете сделать то же самое для любой конкретной версии по вашему выбору.
Почему вам следует установить Python 3.5 или новее
Теперь, когда мы рассмотрели суть дела, давайте поговорим о том, какую версию Python вам следует установить и почему.
Начнем с цифр. Имеет смысл, что с течением времени служебная программа или язык программирования улучшаются с точки зрения функций и производительности. Python 2.0 был выпущен в 2000 году, Python 2.7 — в 2010 году, тогда как Python 3.0 был выпущен в 2008 году, а Python 3.6 — в 2016 году. В последних версиях в вашем распоряжении больше инструментов и библиотек, поэтому имеет смысл использовать более поздние версии. Однако это понятно, если вы намеренно пытаетесь установить устаревшую версию, если какая-то функция, которая вам нужна, была удалена позже.
Python 2.0 по-прежнему используется во многих системах Linux в качестве версии по умолчанию. Некоторые компании также используют Python 2 для всей своей работы. Однако по мере развития технологий все больше и больше компаний переходят на Python3. Например, Instagram перенес свою кодовую базу с Python 2.7 на Python 3 в 2017 году. Точно так же Facebook догоняет и обновляет свою инфраструктуру до Python 3.4 и более поздних версий.
Кроме того, Python 3 легче понять и изучить новичкам. Так что, если вы только начинаете с этого языка программирования, лучше оставить ветеранов старым и начать свой путь со свежей и отчеканенной версии Python. Короче говоря, для тех, кто еще этого не сделал, подумайте об обновлении Python до версии 3.5 или новее.
Вывод
В современную эпоху вычислений уместно, чтобы мы обновляли наши системы, наше программное обеспечение было свободным от вирусов, а наши утилиты обновлялись до последних версий. Таким образом, мы можем сделать наши повседневные задачи проще, проще и точнее. Так что быть программистом или разработчиком помогает иметь последнюю версию Python, работающую в вашей системе.
How to install a specific Python version on Ubuntu
It is often the case that we install a program on our system, and it turns out that it’s the wrong version. This can lead to compatibility and performance issues since it may not communicate with third-party modules properly. Similar is the case with Python, and as vigilant programmers, we must figure out the correct version that we need. Therefore, in this guide, we will show you how to install a specific version of Python on your Ubuntu system.
Python on Ubuntu
Usually, Python comes preinstalled in many Linux distributions. In our case, we have Python3. Start a new Terminal session through the Activities menu or by pressing Ctrl + Alt +T on your keyboard. To be on the safe side of things, you can check whether your distro has Python installed or not by running the following command.
Or, if you are running Python 3 like us, the command below ought to get the job done.
You can see in the image that the system is running Python 3.8.5. It is advised to upgrade your version of Python if you are running Python 3.3 or below. Stick around to find out more on which version you should get, as we will discuss that in the final segment of the article.
In the sections below, we will demonstrate how you can install any version of Python on your system, whether be it an updated one or an outdated one.
Installing a specific version of Python
The first step to installing Python is to install the necessary dependencies and packages that are required for its installation. However, to install these dependencies, you must have the multiverse repository enabled. You can enable it by running the command given below.
Once that is out of the way, we move on to installing the first dependency. Run the command below to proceed.
It should finish downloading and installing in a few moments. Once it is done, move on to the next one by running the command below.
$ sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
It is a long and complicated command so simply copy-paste it into your Terminal to avoid any typing errors.
Having done that, we move on to downloading Python and installing it. For the sake of showing you how to install a specific version, we will be downgrading our Python from 3.8.5 to Python 2.7.
First, we change the current directory to the Downloads folder where we wish to download the package. This can be done by running the command below.
The next step is to “wget” the package from the Python website.
Click here to access the location from where you can select any version of Python of your liking. All that needs to be amended in the wget command is the link.
Having successfully downloaded a specific version of Python, the final steps are simple and easy. First, we will extract the package through the command below.
You can replace the version number as Python-version.tgz according to your package.
The next steps include opening the Python directory, configuring the files, and installing it. Run the commands below in the given order to proceed.
The installation process, while it is straightforward and simple, should take a few minutes to complete. Once it’s done, you can check whether the installation was successful or not by simply running the commands we mentioned at the start.
As you can tell from the image, we have successfully downgraded from Python 3.8.5 to Python 2.7.12. You can do the same for any particular version of your choice.
Why you should install Python 3.5 or later
Now that we have covered the meat of the matter let’s talk about which Python version you should get and why.
Let’s start with the numbers. It makes sense that as time passes by, a utility or programming language progresses in terms of features and performance. Python 2.0 was released in 2000, Python 2.7 in 2010, whereas Python 3.0 was released in 2008, and Python 3.6 in 2016. The latest versions have more tools and libraries at your disposal, so it makes sense to use the later versions. However, it is understandable if you are trying to install an outdated version on purpose if some feature you need was removed later.
Python 2.0 is still used in many Linux systems as the default version. Some companies also use Python 2 for all their work. However, as the technology progresses, more and more companies are moving toward Python3. For instance, Instagram migrated its code-base from Python 2.7 to Python 3 in 2017. Similarly, Facebook is catching up and is upgrading its infrastructure to Python 3.4 and later.
Furthermore, Python 3 is easier to understand and learn for beginners. So if you happen to be just starting off with this programming language, it’s better to leave the veterans to the old ones and start your journey with a fresh and minted version of Python. In short, for those who haven’t already, consider upgrading your Python to version 3.5 or later.
Conclusion
In the modern era of computing, it is pertinent that we keep our systems updated, our software free of viruses, and our utilities upgraded to their latest versions. This way, we can make our daily tasks easier, simpler, and accurate. So being a programmer or developer helps to have the latest version of Python up and running on your system.