- How to Install Latest Python from Source in Linux
- Install Python on Linux from Source
- Install Python IDLE on Linux
- Установка Python на Linux
- Подготовка
- Сборка Python в Linux из исходников
- Установка Python в Linux
- Категории
- Свежие записи
- 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¶
How to Install Latest Python from Source in Linux
Several top universities around the globe use Python to introduce students to programming. The Massachusetts Institute of Technology (MIT), the University of Texas at Arlington, and Stanford are only a few examples of institutions that use this language extensively.
Additionally, it is important to note that Python is also useful for a wide variety of educational, enterprise, and scientific purposes – from web development to desktop applications to machine learning and everything in between.
Currently, there are two major Python versions in use – 2 and 3, with 2 rapidly losing ground to 3 since the former is no longer under active development. Since all Linux distributions come with Python 2.x installed.
In this article, we will show how to install and use the latest Python version in RHEL-based distributions and Debian and its derivatives such as Ubuntu (the latest LTS version already has the latest Python installed) or Linux Mint. Our focus will be installing the core language tools that can be used in the command line.
However, we will also explain how to install Python IDLE – a GUI-based tool that allows us to run Python code and create standalone functions.
Install Python on Linux from Source
At the time of this writing (November 2022), the latest version is Python 3.11, and we are going to perform the installation from the source.
Although we can install the core packages and their dependencies using yum and aptitude (or apt-get) or apt.
Why? The reason is simple: this allows us to have the latest stable release of the language (3.11) and to provide a distribution-agnostic installation method.
Prior to installing Python in RHEL-based distributions such as CentOS Stream Fedora, Rocky, and AlmaLinux, let’s make sure our system has all the necessary development dependencies:
# yum -y groupinstall development # yum -y install zlib-devel
In >Debian-based distributions such as Ubuntu and Linux Mint, we will need to install gcc, make, and the zlib compression/decompression library:
# aptitude -y install gcc make zlib1g-dev
Once needed core packages are installed, you can head over to the official Python download page to download the Python 3.11 source release or use the following wget command to download it directly and install it.
# wget https://www.python.org/ftp/python/3.11.0/Python-3.11.0.tar.xz # tar xJf Python-3.11.0.tar.xz # cd Python-3.11.0 # ./configure # make # make install
Now relax and go grab a sandwich because this may take a while. When the installation is complete, use which to verify the location of the main binary:
# which python3 # python3 -V # python3
The output of the above command should be similar to:
[[email protected]:~/Python-3.11.0]# which python3 /usr/local/bin/python3 [[email protected]:~/Python-3.11.0]# python3 -V Python 3.11.0 [[email protected]:~/Python-3.11.0]# python3 Python 3.11.0 (main, Nov 15 2022, 09:50:56) [GCC 8.5.0 20210514 (Red Hat 8.5.0-10)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> quit Use quit() or Ctrl-D (i.e. EOF) to exit >>> quit()
Congratulations! Python 3.11 is now installed on your system.
Install Python IDLE on Linux
Python IDLE is a GUI-based tool for Python. If you wish to install the Python IDLE, grab the package named idle (Debian) or python-tools (RHEL).
# yum install python3-idle [On RHEL/CentOS/Fedora and Rocky Linux/AlmaLinux] # apt-get install idle [On Debian, Ubuntu and Mint]
Type the following command to start the Python IDLE.
Summary
In this article, we have explained how to install the latest Python stable version from the source.
Last, but not least, if you’re coming from Python 2, you may want to take a look at the 2to3 official documentation. This is a program that reads Python 2 code and transforms it into valid Python 3 code.
Do you have any questions or comments about this article? Feel free to get in touch with us using the form below.
Установка Python на Linux
В этой заметке я покажу как собрать из исходников и установить Python на Linux. Я буду все действия производить на Ubuntu 20.04, но инструкция будет одинаково работать и на LinuxMint и Debian.
В моей Ubuntu по умолчанию установлен Python 3.8.10, я хочу установить более свежую версию, как же это сделать?
Подготовка
Устанавливаем все необходимое для сборки Питона из исходников
sudo apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev libsqlite3-dev wget libbz2-dev
Дальше на странице https://www.python.org/downloads/source/ нужно сохранить ссылку на исходники нужной вам версии Python, например я возьму последнюю на данный момент версию Python 3.10.1
С помощью wget скачиваем исходники в домашнюю директорию
sudo wget https://www.python.org/ftp/python/3.10.1/Python-3.10.1.tgz
Далее разархивируем скаченный архив:
sudo tar -xf Python-3.10.1.tgz
Сборка Python в Linux из исходников
Перейдем в директорию с исходным кодом Python
Далее нужно запустить скрипт конфигурации, он выполнит проверки на необходимые для сборки Python
Мы запускаем скрипт с параметром —enable-optimizations, он оптимизирует собираемый двоичный файл Python (правда это замедлит процесс сборки, https://docs.python.org/3/using/configure.html).
После выполнения скрипта нам остается запустить сам процесс сборки:
Параметром -j 4 я указал количество ядер процессора, узнать эту цифру можно командой nproc .
Установка Python в Linux
Процесс сборки довольно длительная операция, после того, как она завершиться можно установить Python одной из двух команд:
Эта команда устанавливает наш Python рядом с предыдущими версиями, в будущем вы сможете выбирать какой версией пользоваться.
Эта команда установит новую версию Python поверх старых.
В данный момент я воспользовался первой командой altinstall .
Дожидаемся окончания процесса установки и проверяем:
В ответ получаем версию Python 3.10.1
Предыдущая версия python, установленная в Убунту 20.04 по умолчанию так же доступна, можно убедится в этом вызвав команду:
В ответ получаем версию Python 3.8.10
Теперь можно удалить архив с исходниками и папку куда мы их разархивировали:
sudo rm -Rf Python-3.10.1 Python-3.10.1.tgz
Еще раз повторюсь, что инструкция выше по сборке Python из исходников в Ubuntu подойдет и для установки Python в LinuxMint и Debian. В репозиториях этих дистрибутивов уже есть собранные Python, но не всегда самой свежей версии.
Категории
Свежие записи
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:
2.1.2. On FreeBSD and OpenBSD¶
pkg_add -r python pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages//python-.tgz
pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2.tgz
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:
./configure make make install
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 and exec_prefix are installation-dependent and should be interpreted as for GNU software; they may be the same.
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.
$ find /etc/ -name openssl.cnf -printf "%h\n" /etc/ssl
$ curl -O https://www.openssl.org/source/openssl-VERSION.tar.gz $ tar xzf openssl-VERSION $ pushd openssl-VERSION $ ./config \ --prefix=/usr/local/custom-openssl \ --libdir=lib \ --openssldir=/etc/ssl $ make -j1 depend $ make -j8 $ make install_sw $ popd
$ pushd python-3.x.x $ ./configure -C \ --with-openssl=/usr/local/custom-openssl \ --with-openssl-rpath=auto \ --prefix=/usr/local/python-3.x.x $ make -j8 $ make altinstall
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.