- 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¶
- Установка Python на Linux
- Подготовка
- Сборка Python в Linux из исходников
- Установка Python в Linux
- Категории
- Свежие записи
- How to install Python on Linux
- 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
- Step 3: Extract the tarball
- Step 4: Configure the script
- Step 5: Start the build process
- Step 6: Verify the installation
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.
Установка 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, но не всегда самой свежей версии.
Категории
Свежие записи
How to install Python on Linux
Step-by-step instructions for installing the latest Python instead of (or alongside) an older version 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:
$ sudo apt update $ sudo apt install build-essential zlib1g-dev \ libncurses5-dev libgdbm-dev libnss3-dev \ libssl-dev libreadline-dev libffi-dev curl
On Fedora:
$ sudo dnf groupinstall development
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.