- Fedora Developer Portal
- Multiple Python interpreters
- Getting it and running it all with tox
- Creating virtual environments and installing packages
- Python 3 (including PyPy 3)
- Python 2.7, PyPy 2
- MicroPython
- Установка Python в CentOS 8 и RHEL 8
- Установка Python 2
- Шаг 1. Обновление среды
- Шаг 2: Установите Python 2
- Шаг 3: Проверьте установку Python 2
- Шаг 4: Запуск Python 2
- Установка Python 3
- Шаг 1. Обновление среды
- Шаг 2: Установите Python 3
- Шаг 3: Проверьте установку Python 3
- Шаг 4: Запуск Python 3
- Установка версии Python по умолчанию
Fedora Developer Portal
General-purpose, high-level programming language supporting multiple programming paradigms.
Multiple Python interpreters
If you are working on a piece of Python software, you probably want to test it on multiple Python interpreters. On Fedora, that’s easy: all you have to do is use dnf to install what you need.
Fedora includes all Python versions which are supported upstream, a few older ones and possibly a pre-release of a newer one.
At the time of this writing, Fedora has the following Pythons ready for you in the repositories:
- CPython 3.11
- CPython 3.10
- CPython 3.9
- CPython 3.8
- CPython 3.7
- CPython 3.6
- CPython 2.7
- PyPy 2
- PyPy 3.7
- PyPy 3.8
- PyPy 3.9
- MicroPython
Quite a nest, isn’t it? You can install them like this:
$ sudo dnf install python3.9 # to get CPython 3.9 $ sudo dnf install python3.8 # to get CPython 3.8 $ sudo dnf install python3.7 # to get CPython 3.7 $ sudo dnf install python3.6 # to get CPython 3.6 $ sudo dnf install python2.7 # to get CPython 2.7 $ sudo dnf install pypy2 pypy3.9 python3.10 # to get more at once
After that, you can run an interactive console or your script with, let’s say, CPython 3.6:
$ python3.6 Python 3.6.12 (default, Aug 19 2020, 00:00:00) [GCC 10.2.1 20200723 (Red Hat 10.2.1-1)] on linux Type "help", "copyright", "credits" or "license" for more information. >>>
Warning: For production purposes you should use the python3 package only. Other CPython versions might be unstable or even dangerous (either because they are extremely old or quite the contrary alpha/beta quality) and are intended solely for development.
Getting it and running it all with tox
Tox is tool that helps you test your Python code on multiple Pythons. If you install it on Fedora via the dnf package manager, you’ll automatically get all supported CPythons and PyPys:
If you are not yet familiar with tox, don’t worry. This short example will show you how to start.
Let’s create a directory and a simple Python file in it that will say something nice:
# say.py print('Fedora is the best OS for Python developers', end='\n\n')
Now we’ll test if it works with all the Pythons, with tox. We’ll create a simple configuration file for tox, tox.ini , in the same directory:
[tox] envlist = py27,py37,py38,py39,pypy,pypy3 skipsdist = True [testenv] commands=python say.py
The envlist directive defines the list of Pythons to test on. Normally, tox assumes you are testing a project with its own setup.py . For the simplicity of this demo, we are not using it, and we need to tell this to tox via the skipsdist option. Finally the commands in the [testenv] section tells tox what commands to run for the test. Normally, that would be python setup.py test , pytest or similar.
With tox.ini in place, run tox in the same directory:
$ tox [. ] ERROR: py27: commands failed py37: commands succeeded py38: commands succeeded py39: commands succeeded ERROR: pypy: commands failed pypy3: commands succeeded
As you can see, there’s something wrong with the script: it only works on Python 3. The full tox output (omitted here) contains the exact error. If you want to support old Python 2 as well, you’ll have to fix it:
# say.py from __future__ import print_function print('Fedora is the best OS for Python developers', end='\n\n')
$ tox [. ] py27: commands succeeded py37: commands succeeded py38: commands succeeded py39: commands succeeded pypy: commands succeeded pypy3: commands succeeded congratulations :)
If you want to use tox for your projects, you can learn more at the documentation.
Creating virtual environments and installing packages
Fedora only packages Python modules for one current version of python3 . For all other interpreters, you will need to install packages from PyPI, the Python Package Index.
The best way is to use Python virtual environments. The invocation to create them differs for different Python versions. Packages installed in a virtual environment are only available once the environment is activated. Here you can see two demos that create a virtual environment in a folder named env and install some package into it.
Python 3 (including PyPy 3)
Recent versions of Python 3 include the venv module, which can create virtual environments. See the PyPI & pip section for details.
$ python3.9 -m venv env # create the environment $ source env/bin/activate # activate it (env)$ python -m pip install requests # install a package with pip . (env)$ python # run python from that environment Python 3.9.0 (default, Oct 6 2020, 00:00:00) [GCC 10.2.1 20200723 (Red Hat 10.2.1-1)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import requests >>> . >>> exit() (env)$ deactivate # go back to "normal"
The environment is a directory. If you no longer need it, deactivate it and delete it with rm -rv env .
Python 2.7, PyPy 2
For other Python versions, a tool called virtualenv can create virtual environments:
$ sudo dnf install /usr/bin/virtualenv # install the necessary tool $ virtualenv --python /usr/bin/python2.7 env # create the virtualenv Running virtualenv with interpreter /usr/bin/python2.7 New python executable in env/bin/python2.7 Also creating executable in env/bin/python Installing setuptools, pip. done. $ source env/bin/activate # activate it (env)$ python -m pip install requests # install a package with pip . (env)$ python # run python from that virtualenv Python 2.7.11 (default, Jul 8 2016, 19:45:00) [GCC 5.3.1 20160406 (Red Hat 5.3.1-6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import requests >>> . >>> exit() (env)$ deactivate # go back to "normal"
MicroPython
MicroPython does not support virtual environments. It does have a rudimentary pip replacement called upip, which you can use to install packages that support MicroPython. Run it to find out more:
Установка Python в CentOS 8 и RHEL 8
Python — один из самых популярных языков программирования. Однако в CentOS 8 он не установлен по-умолчанию.
В более ранних выпусках CentOS по умолчанию была доступна неверсированная команда Python. После установки CentOS, можно было перейти в оболочку Python, просто запустив команду «python» в терминале. Как это ни парадоксально, CentOS 8 не имеет неверсионной команды Python по умолчанию. Напрашивается вопрос, почему? RedHat заявляет, что этот выбор сделан «чтобы избежать блокировки пользователей в конкретной версии Python». В настоящее время RedHat 8 неявно использует Python 3.6 по умолчанию, хотя Python 2.7 дополнительно предоставляется для поддержки существующего программного обеспечения. Ранее неверсионная команда Python в дистрибутивах CentOS, хотя и была удобной, создавала определенные проблемы. Неверсионный Python обычно указывает на интерпретатор Python 2, но поскольку Python 2 сейчас находится на EOL (конец срока службы), это становится проблематичным по нескольким причинам. Простое перенаправление команды на Python 3 может показаться несложным решением, но на многих уровнях это будет проблематично из-за возможной путаницы с версионированием. Вместо того, чтобы продолжать указывать команду «python» на версию Python по умолчанию из-за знакомства или указывать на Python 3, чтобы идти в ногу со временем, был сделан выбор больше не включать стандартную команду «python».
В этом руководстве мы рассмотрим установку как активно используемой версии Python 2, так и новой версии Python 3 в CentOS 8 и Red Hat Enterprise Linux (RHEL) 8.
Установка Python 2
Шаг 1. Обновление среды
Всегда полезно начинать с проверки того, что все наши системные пакеты обновлены перед установкой нового программного обеспечения. Для этого мы собираемся воспользоваться новым программным обеспечением для управления пакетами DNF.
Шаг 2: Установите Python 2
Теперь, когда среда обновлена, давайте продолжим и будем использовать DNF для установки Python 2. К счастью, и Python 2, и 3 включены в репозитории базовых пакетов CentOS 8, поэтому установка выполняется просто.
Шаг 3: Проверьте установку Python 2
Чтобы убедиться, что Python 2 установлен, мы можем запустить простую команду «python2» с флагом версии.
Шаг 4: Запуск Python 2
Впоследствии, чтобы получить доступ к оболочке Python 2, мы можем выполнить следующую команду.
# python2 Python 2.7.16 (default, Nov 17 2019, 00:07:27) [GCC 8.3.1 20190507 (Red Hat 8.3.1-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>
Готово! Python 2 теперь установлен! Следует отметить, что PIP-установщик пакетов Python также устанавливается по умолчанию при установке Python 2, поэтому вы сможете сразу начать работу с пакетами Python.
Установка Python 3
Шаг 1. Обновление среды
Еще раз давайте убедимся, что наши системные пакеты обновлены.
Шаг 2: Установите Python 3
Теперь мы готовы установить Python 3.
Шаг 3: Проверьте установку Python 3
Мы можем проверить установку и версию Python 3 так же, как и в Python 2.
Шаг 4: Запуск Python 3
Затем мы можем войти в среду оболочки Python 3, выполнив следующую команду.
# python3 Python 3.6.8 (default, Nov 21 2019, 19:31:34) [GCC 8.3.1 20190507 (Red Hat 8.3.1-4)] on linux Type "help", "copyright", "credits" or "license" for more information. >>>
Как и в случае установки Python 2, pip3 также включается при установке Python 3. Вот и все! Теперь можно начинать работу с Python на вашем сервере CentOS 8.
Установка версии Python по умолчанию
Вы должны были заметить, что для использования Python 3, это команда python3 и python2 для Python 2. Что делать, если ваши приложения настроены на обращение к python, который недоступен для всей системы?
# python bash: python: command not found.
Вы можете использовать механизм альтернатив, чтобы включить неверсированную команду python для всей системы и установить для нее определенную версию:
# alternatives --set python /usr/bin/python3
# alternatives --set python /usr/bin/python2
Чтобы посмотреь настроенную версию Python по умолчанию используйте следующую команду:
Чтобы сбросить эту конфигурацию и удалить неверсионную команду python, выполните: