Как установить Python на Linux
В последнее время, среди нового поколения разработчиков программного обеспечения большую популярность набирает язык программирования Python (Питон). На примере Python, мы видим высокоуровневый язык, который не нуждается в компиляторе и применяется для написания самого разного вида софта (мобильные приложения, веб-разработка, СПО под Линукс, системы искусственного интеллекта и machine learning, Data Science и др.). Надо отметить, что профессия программиста на Python сейчас достаточно популярна и востребована среди молодежи, ей обучают на многочисленных курсах, да и предложения по зарплате очень даже неплохие.
Так как программы, разработанные на Python, не компилируются, то роль интерпретатора байт-кода играет CPython. Исходный код программ, написанных на питоне, хранится в файлах с расширением .py.
В ОС Linux язык Python играет важную роль, он используется для системного администрирования, и именно на нем написаны такие известные программы, как GIMP, Blender и др. В Линукс интерпретатор питон уже установлен «по умолчанию», но как правило, разработчику необходима или наиболее свежая версия или же несколько версий Python сразу. На сегодня, последняя стабильная версия языка Python — это 3.9.2, скачать ее можно на официальном сайте проекта.
В этой статье мы расскажем все тонкости установки Python для Linux, на примере Ubuntu 20, Debian 10, а также CentOS 7/8.
Подготовка к установке Python под Ubuntu 20 (Debian 10)
Как мы уже писали ранее, Python должен быть установлен «по умолчанию» в стандартном пакете сборки Ubuntu 20.04. Перед выполнением инсталляционных работ, наша задача — проверить какая версия питон у нас уже установлена в системе. Сделать это можно с помощью следующей команды:
В нашей ОС Ubuntu 20 уже есть версия Python 3.8.5. Существует еще одна полезная команда, с помощью которой можно узнать, какие вообще версии Python установлены в нашей ОС Линукс, см. ниже на скриншоте:
Сейчас мы покажем, как установить Python на Ubuntu двумя популярными способами:
- с помощью apt (используя deadsnakes PPA);
- из исходников, скачанных с официального сайта.
Все команды следует выполнять или под пользователем root, или используя sudo.
Установка новой версии Python из deadsnakes PPA
Первоначально, введем команды для обновления списка пакетов и установки необходимых нам для дальнейшей работы библиотек:
Затем необходимо включить deadsnakes PPA (Personal Package Archive), для этого выполним следующую команду:
После этого действия, еще раз выполним команду:
Сейчас установим версию Python 3.9:
На следующем этапе, мы опять проверим список установленных в системе версий Python и видим, что добавилась версия 3.9:
Сборка Python 3.9.2 в Linux из исходников
Этот способ может показаться немного сложнее предыдущего, но зато с помощью него можно установить самую свежую версию Python, которая доступна на официальном сайте. Процесс установки опробован на ОС Ubuntu 20, также его можно применять и на Debian 10.
Зайдем на FTP сервер официального сайта проекта Python (https://www.python.org/ftp/python) и выберем там архив с последней стабильной версией питон:
Перед началом процесса работ по установке выполним команды для обновления системы:
На следующем шаге, необходимо инсталлировать необходимые нам для работы пакеты:
Затем перейдем в папку /tmp и скачаем в нее архив с официального сайта Python*:
*Примечание: можно использовать как команду wget, так и команду curl.
Cейчас распакуем этот архив во временную папку и затем его сразу же и удалим:
На следующем этапе, запустим команду, которая выполнит подготовку к установке (enable-optimization — служит для оптимизации двоичного файла Python). Исполнение данной команды займет некоторое время:
Для того, чтобы начать процесс сборки, выполним команду*:
*Примечание: цифра 2 указывает на количество ядер процессора. Узнать эти данные можно с помощью команды nproc.
Если в процессе сборки будут замечены проблемы, то необходимо запустить сборку в однопоточном режиме, следующим образом (без параметров -j 2), просто выполнив команду make.
Теперь установим Python 3.9.2 с помощью команды altinstall, последняя версия Python инсталлируется наряду со старыми версиями, т.е. у вас в ОС будет несколько версий языка Python. Если же вы используете команду install, то новая версия питон будет установлена поверх старых (а все старые версии будут удалены).
*Процесс инсталляции Python путем сборки пакета из исходников может занять длительное время.
В результате, в нашей ОС Ubuntu 20 (Debian 10) будет установлено сразу несколько версий языка Python, у нас конкретно — это версии 3.9.2 и 3.8.5, проверить можно с помощью команд:
Особенности установки Python на CentOS
Для инсталляции Python на CentOS версии 7 необходимо использовать репозиторий epel (Extra Packages for Enterprise Linux) или же DNF (Dandified YUM, т.е. yum нового поколения) для CentOS 8.
Для способа с использованием DNF выполним следующие команды:
- Проверим обновления нашего диспетчера пакетов:
- Установим стабильную версию Python 3 из репозитория:
- Проверим, какая точно версия Python у нас инсталлировалась:
- Чтобы установить инструментарий для разработчиков, выполним следующую команду:
Если же вы будете использовать репозиторий epel, то следуйте простым инструкциям:
- Подключите репозиторий epel для начала работы:
- Затем установите Python (например, версии 3.6):
- Для проверки номера версии введите команду:
- Для отображения последней установленной в вашей ОС версии используйте команду:
Как создать и настроить виртуальную среду
Для чего нужна виртуальная среда? С помощью виртуальной среды мы можем для каждого своего проекта на языке Python выделить отдельную область (со своими зависимостями, с установленными модулями питон, разными версиями языка и т.д.).
Работа с пакетом virtualenv
Например, у нас есть Project A и Project B, для каждого из них мы можем создать свою виртуальную среду, сделать это можно с помощью venv, выполнив несложные команды:
- Создаем каталог для нового проекта my_project и переходим в него:
- Выполним команду, чтобы создать виртуальную среду:
- На данном этапе необходимо ее активировать:
На скриншоте ниже показано, что далее работа с проектом ведется уже внутри виртуальной среды:
Работа с виртуальной средой с помощью virtualenvwrapper и pip
Все действия исполняем для пользователя root, чтобы перейти в root, выполним команду:
-
Для начала устанавливаем менеджер пакетов pip:
Добавим в конец файла следующие строки:
Сохраним изменения и закроем файл.
А) Для создания новой виртуальной среды (например, ansible) используется команда:
Б) Для удаления виртуальной среды:
В) Чтобы активировать нужную вам виртуальную среду:
Г) Для выхода из среды:
Д) Показать список установленных пакетов:
Е) Для инсталляции конкретных пакетов:
Заключение
В этой статье мы рассказали нашим читателям об использовании языка программирования Python и подробно изложили два способа установки последней версии Python для ОС Linux (на Ubuntu 20, Debian 10, CentOS 7 и 8). Также дали основные понятия о работе с виртуальной средой.
How to install Python on Linux?
Before we start with how to install Python3 on Linux, let’s first go through the basic introduction to Python. Python is a widely-used general-purpose, high-level programming language. Python is a programming language that lets you work quickly and integrate systems more efficiently. There are two major Python versions- Python 2 and Python 3. Both are quite different.
Getting started with Python
Python is a lot easier to code and learn. Python programs can be written on any plain text editor like notepad, notepad++, or anything of that sort. One can also use an online IDE for writing Python codes or can even install one on their system to make it more feasible to write these codes because IDEs provide a lot of features like intuitive code editor, debugger, compiler, etc.
To begin with, writing Python Codes and performing various intriguing and useful operations, one must have Python installed on their System. This can be done by following the step by step instructions provided below:
What if Python already exists? Let’s check
Most of the Linux OS has Python pre-installed. To check if your device is pre-installed with Python or not, just go to terminal using Ctrl+Alt+T
Now run the following command:
For Python2
For Python3.x
If Python is already installed, it will generate a message with the Python version available.
Download and Install Python:
Before starting with the installation process, you need to download it. For that all versions of Python for Linux are available on python.org.
Download the required version and follow the further instructions for the installation process.
Beginning the installation.
For almost every Linux system, the following command could be used to install Python directly:
- Getting Started:
- Assigning DiskSpace:
- Fetching and Installing Packages:
- Getting through the installation process:
- Finished Installation:
To verify the installation enter the following commands in your Terminal.
How to Install Python on Linux?
In this article, you will learn all about starting your journey with this Python tutorial by installing and interacting with Python for Linux. Follow the steps and start coding in no time!
Introduction
Rahul recently read an article on "what is Python?" and came across all the amazing things he can create and achieve using Python. Rahul is highly intrigued and wishes to start his Python journey immediately. This is no surprise, as Python is a widely-used, high-level programming language used across various disciplines.
Well, if this sounds anything like you, then you are at the right place! The first step to becoming a Pythoneer or a Pythonista, if you are a Linux user, is to know the answer to the question “How to Install Python on Linux and interact with it?”
Prerequisite to Install Python on Linux
You will need certain prerequisites to be met before you successfully know how to install Python on Linux. They are as follows-
- A computer running on Debian / Fedora OS with a minimum of 2GB RAM (4GB Preferable) and 5GB of disk space
- Also, you need sudo access on the system you want to install Python on Linux
sudo command: It allows you to temporarily elevate your current user account to have root privileges.
How to Check the Python Version on Linux?
Python comes preinstalled on most of the Linux distributions like Debian.
You can simply check the Python Version, which is already installed on your system, by running python -V or python —version command on your terminal.
When Python is not already installed: The output will be something like this-
When Python is already Installed: The output will be something like this-
Python x.x.x For example, Python 3.8.5-
Two Ways to Install Python on Linux
- Install Python on Linux from Package Manager
- Build from Source Code
I. Install Python on Linux from Package Manager:
The following command could be used to install the latest version of Python on almost every Linux system.
Also, you can mention the particular version of Python you want to install, shown below :
Type Y and press Enter to continue. The Package manager will download and install the Python for you.
II. Build from source code
Before starting, please make sure that you have git , gcc , and make installed on your system.
Steps to be followed to Build Python from Source Code:
- Get the source code
- Configure
- Build
1. Get the Source code:
We can clone the latest Python source code from Python’s official GitHub repository using git to install Python on Linux.
2. Configure:
The configuration script comes with the source code that can be passed through many flags.
Some important flags are:
- —prefix : Used to determine where the final built files go
- —enable-optimizations — Enable Profile Guided Optimization (PGO) using PROFILE_TASK (disabled by default). Optimization takes a long time to configure, but the resulting python binary interpreter is 10% faster at executing Python code.
- Navigate to the cpython directory where we have cloned Python source code-
- Then run the below command on your Terminal to configure-
- If you want to add —enable-optimizations flag then the command will be-
Note: $HOME will contain the path to the current user’s home directory. You can check your home directory by using the echo command.
Your terminal will show something like this once the configuration is done —
3. Build
- Once the configuration is done, we are ready to start the build process.
- Run the make tool to build the files, followed by the make install command to put the built files in the location specified by configure's —prefix .
- The final output of the make command will be something like this —
- The output of make install will be like this —
Step by Step Guide to Install Python on Linux
- Step 1 — Install Development Packages Required to Install Python on Linux-
- On Debian
- On Fedora
- Step 2 — Download the Latest Version of Python
- Step 3 — Extract the tar file to install Python on Linux
- Step 4 — Configure the Script
- Step 5 — Getting Through the steps to install Python on Linux and finishing installation
- Step 6 — Verify the Installation
- Step 7 — Create Virtual Environment(Optional)
1. Install Development Packages Required to install Python on Linux:
On Debian: Follow the below steps to install the development packages required to install Python on Linux (Debian system)-
Ensure you have enabled the source packages in the sources list. You can do this by adding the location of the source packages, including URL, distribution name, and component name, to /etc/apt/sources.list .
Take Ubuntu Bionic, for example:
For other distributions, like Debian, change the URL and names to correspond with the specific distribution.
Update the package index using the following command-
Install the Python Build dependencies: You can install the build dependencies by running the below command on your Terminal.
If you want to build all optional modules, install the following packages and their dependencies:
On Fedora:
- yum-based systems:
- dnf based systems:
Step 2- Download latest version of Python:
You can download the latest version of Python as tar file by visiting python.org.
Just click on the download button to download the tar file. Note: At the time of writing this article, the latest version of Python was 3.9.6.
Step 3- Extract the tar file to install Python on Linux:
Once the download is completed, open the Terminal and navigate to the Downloads directory.
Run the below tar command to extract the files-
In our case the name of the downloaded file is Python-3.9.6.tar.xz . So the command will be-
The above command will create a directory in the name of the file (without file extension). So the name of the directory will be Python-3.9.6 .
Step4- Configuring the Script:
Follow the Configure and Build steps of Build from source code.
Let's create an alias for Python 3.9 so the version will not confuse us. An alias can be easily created by using alias commands like those given below.
Step 5- Getting Through the steps to install Python on Linux and finishing installation
In this step, you have to let the system do its thing and wait for it to install Python on Linux.
Step 6- Verify the installation:
You are so close to completing the installation of Python on Linux! Now, open any of your favorite code/text editors and add the below code.
Save the file with the .py extension. For example, helloworld.py .
Open terminal inside the directory where you saved the .py file. And run the program file using the python command.
The output of the program-
Step 7- Create Virtual Environment(Optional) :
There are many ways to create a Python virtual environment after you have learnt how to install Python on Linux. Here we are going to see how to create a python virtual environment using the virtual environment package which comes with Python3.
You can create a Python virtual environment by just running the below command on your Terminal.
Replace test_env with the path where you want to store your virtual environment
Then verify the created virtual environment by using the ls command shown in the above picture.
You may get the output as shown in the picture below if the Python virtual environment is not installed already.
In this case, you can install the package by using the below command-
Press Y and Enter to continue the installation.
Now again, try to run the command to create the virtual environment.
The newly created virtual environment can be activated by using the source command-
How to install Python on Linux
Python is now the most popular, most used programming language. Python’s simple syntax and low learning curve make it the ultimate choice for beginners as well as professional developers. Python is also a very versatile programming language. It’s used nearly everywhere—from web development to artificial intelligence—really anywhere other than mobile development.
If you’re using Python, there’s a good chance you’re a developer (or want to become one), and Linux is a great platform for creating software. But when you’re working with Python every day, you sometimes want to stay up to date with the very latest version. You may not want to replace the default install of Python on your system just to test drive the latest one, so this article explains how to install the latest version of Python 3 on Linux without replacing the version provided by your distribution.
Use the python —version terminal command to check whether Python is already installed and, if so, which version you have. If Python is not installed on your Linux system, or you want to install an updated version, follow the steps below.
Step-by-step installation instructions
Step 1: First, install development packages required to build Python.
On Debian:
On Fedora:
Step 2: Download the stable latest release of Python 3
Visit the official Python website and download the latest version of Python 3. After the download is complete, you hav a .tar.xz archive file (a «tarball») containing the source code of Python.
Step 3: Extract the tarball
Once the download is complete, extract the tarball by either using the extractor application of your choice or the Linux tar command, for example:
Step 4: Configure the script
Once the Python tarball has been extracted, navigate to the configure script and execute it in your Linux terminal with:
The configuration may take some time. Wait until it is successfully finishes before proceeding.
Step 5: Start the build process
If you already have a version of Python installed on your system and you want to install the new version alongside it, use this command:
The build process may take some time.
If you want to replace your current version of Python with this new version, you should uninstall your current Python package using your package manager (such as apt or dnf) and then install:
However, it’s generally preferable to install software as a package (such as a .deb or .rpm file) so your system can track and update it for you. Because this article assumes the latest Python isn’t yet packaged yet, though, you probably don’t have that option. In that case, you can either install Python with altinstall as suggested, or rebuild an existing Python package using the latest source code. That’s an advanced topic and specific to your distribution, so it’s out of scope for this article.
Step 6: Verify the installation
If you haven’t encountered any errors, the latest Python is now installed on your Linux system. To verify it, write one of these commands in your terminal:
If the output says Python 3.x, Python 3 has been successfully installed.