- 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
- Contents
- Installation
- Python 3
- Python 2
- Alternative implementations
- Alternative shells
- Old versions
- Package management
- Widget bindings
- Tips and tricks
- Virtual environment
- Tab completion in Python shell
- Как установить Python на Linux
- О языке программирования Python
- Подготовка к установке Python под Ubuntu 20 (Debian 10)
- Установка новой версии Python из deadsnakes PPA
- Сборка Python 3.9.2 в Linux из исходников
- Особенности установки Python на CentOS
- Как создать и настроить виртуальную среду
- Работа с пакетом virtualenv
- Работа с виртуальной средой с помощью virtualenvwrapper и pip
- Заключение
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.
Источник
Python
Python is an interpreted, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes. It supports multiple programming paradigms beyond object-oriented programming, such as procedural and functional programming. Python combines remarkable power with very clear syntax. It has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface. Finally, Python is portable: it runs on many Unix variants including Linux and macOS, and on Windows.
Contents
Installation
Python 3
Python 3 is the latest and actively developed version of the language. See What’s New in Python to see the latest changes in Python 3.
To install the current release of Python 3, install the python package.
If you would like to build the latest RC/betas from source, visit Python Downloads. The Arch User Repository also contains good PKGBUILDs. If you do decide to build the RC, note that the binary (by default) installs to /usr/local/bin/python3.x . As an alternative which does not require superuser capabilities and installs to the home directory, consider using pyenv .
Python 2
Python 2 is an older version of the language. Python 3 and Python 2 are incompatible. For an overview of the differences, see the historical version of the Python2orPython3 document.
Although Python 2 is no longer actively maintained, there are some packages that still depend on it. Python 2 may also be useful for developers maintaining, using or porting legacy Python 2 software.
To get the latest version of Python 2, install the python2 package.
Python 2 will happily run alongside Python 3. You need to specify python2 in order to run this version.
Any program requiring Python 2 needs to use /usr/bin/python2 , instead of /usr/bin/python , which points to Python 3. However, many legacy Python 2 scripts incorrectly specify python in their shebang line. To change this, open the program or script in a text editor and change the first line. The line may show one of the following:
In either case, change python to python2 and the program will then use Python 2 instead of Python 3.
Another way to force the use of python2 without altering the scripts is to call it explicitly with python2 :
Finally, you may not be able to control the script calls, but there is a way to trick the environment. It only works if the scripts use #!/usr/bin/env python . It will not work with #!/usr/bin/python . This trick relies on env searching for the first corresponding entry in the PATH variable.
First create a dummy folder:
Then add a symlink python to python2 and the config scripts in it:
Finally put the new folder at the beginning of your PATH variable:
To check which python interpreter is being used by env , use the following command:
A similar approach in tricking the environment, which also relies on #!/usr/bin/env python to be called by the script in question, is to use a virtual environment.
Alternative implementations
The python package installs CPython, the reference implementation of Python. However, there are also other implementations available. These implementations are usually based on older versions of Python and are not fully compatible with CPython.
Implementations available on Arch Linux include:
- PyPy — A Python implementation written in Python. It has speed and memory usage advantages compared to Cython.
https://www.pypy.org || pypy , pypy3
- Jython — An implementation of the Python language written in Java. It can be used to embed Python scripting into Java programs or use Java libraries in Python programs.
https://www.jython.org/ || jython
- micropython — Python for microcontrollers. It includes a small subset of the Python standard library and is optimized to run on microcontrollers and in constrained environments.
https://micropython.org/ || micropythonAUR
- IronPython — An implementation of the Python programming language which is tightly integrated with .NET. It can use .NET libraries and allows .NET programs to use Python libraries.
https://ironpython.net || ironpython-gitAUR
More implementations exist. Some, such as Stackless, Pyston and Cinder are used internally at large technology companies. Others are historically notable but are no longer maintained due to improvements in the most popular implementations.
Alternative shells
The python package includes an interactive Python shell/REPL which can be launched with the python command. The following shells are also available:
Old versions
Old versions of Python are available via the AUR and may be useful for historical curiosity, old applications that do not run on current versions, or for testing Python programs intended to run on a distribution that comes with an older version:
Extra modules/libraries for old versions of Python may be found on the AUR by searching for python , e.g. searching for python26 for 2.6 modules.
Package management
There are several ways to install Python packages on Arch Linux:
- Official repositories and AUR — A large number of popular packages are available in the Arch repositories. This is the preferred way to install system-wide packages.
- pip(1) — The official package installer for Python. You can use pip to install packages from the Python Package Index and other indexes.
https://pip.pypa.io/ || python-pip
- pipx — Closely related to pip, but creates, for the user running it, an isolated environment for each application and its associated packages, preventing conflicts with system packages. Focused on packages that can be run from the command line directly as applications. You can use pipx to install packages from the Python Package Index and other indexes.
https://pypa.github.io/pipx/ || python-pipx
- Anaconda — An open source package management system and environment management system, originally created for Python programs. You can use Conda to install packages from the Anaconda repositories.
https://docs.conda.io/projects/conda/ || anacondaAUR
- Miniconda — A lightweight alternative to Anaconda which installs the package manager but does not install scientific computing packages by default.
https://docs.conda.io/en/latest/miniconda.html || miniconda3AUR
When installing packages using pip, it is recommended to use a virtual environment to prevent conflicts with system packages in /usr . Alternatively, pip install —user can be used to install packages into the user scheme instead of /usr . pipx and Conda integrate environment management into their workflows.
See the Python Packaging User Guide for the official best practices for package management.
Historically, easy_install (part of python-setuptools ) was used to install packages distributed as Eggs. easy_install and Eggs have been replaced with pip and Wheels. See pip vs easy_install and Wheel vs Egg for more information.
Widget bindings
The following widget toolkit bindings are available:
To use these with Python, you may also need to install the associated widget toolkit packages (e.g. tk must also be installed to use Tkinter).
Tips and tricks
Virtual environment
Python provides tools to create isolated virtual environments into which packages may be installed without conflicting with other virtual environments or the system packages. Virtual environments can also run applications with different versions of Python on the same system.
Tab completion in Python shell
Tab completion is available in the interactive shell by default. Note that the readline completer will only complete names in the global namespace. You can use python-jedi for a richer tab completion experience [1].
Источник
Как установить Python на Linux
Оглавление
О языке программирования Python
В последнее время, среди нового поколения разработчиков программного обеспечения большую популярность набирает язык программирования 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:
Осуществим установку virtualenv и virtualenvwrapper:
Затем необходимо отредактировать файл .bashrc (в директории пользователя root, если работаете под root или же в директории другого пользователя):
Добавим в конец файла следующие строки:
Сохраним изменения и закроем файл.
А) Для создания новой виртуальной среды (например, ansible) используется команда:
Б) Для удаления виртуальной среды:
В) Чтобы активировать нужную вам виртуальную среду:
Г) Для выхода из среды:
Д) Показать список установленных пакетов:
Е) Для инсталляции конкретных пакетов:
Заключение
В этой статье мы рассказали нашим читателям об использовании языка программирования Python и подробно изложили два способа установки последней версии Python для ОС Linux (на Ubuntu 20, Debian 10, CentOS 7 и 8). Также дали основные понятия о работе с виртуальной средой.
Источник