Как узнать версию python linux
Перейти к содержимому

Как узнать версию python linux

  • автор:

Как проверить версию Python

Python — один из самых популярных языков программирования в мире. Он используется для разработки веб-сайтов, написания скриптов, машинного обучения, анализа данных и многого другого.

В этой статье объясняется, как с помощью командной строки проверить, какая версия Python установлена в вашей операционной системе. Это может быть полезно при установке приложений, которым требуется определенная версия Python.

Мы также покажем вам, как программным способом определить, какая версия Python установлена в системе, в которой выполняется скрипт Python. Например, при написании сценариев Python вам необходимо определить, поддерживает ли сценарий версию Python, установленную на машине пользователя.

Управление версиями Python

Python использует семантическое управление версиями . Версии готовых к выпуску релизов представлены по следующей схеме:

Например, в Python 3.6.8 3 — основная версия, 6 — дополнительная версия, а 8 — микроверсия.

  • MAJOR — Python имеет две основные версии, которые не полностью совместимы: Python 2 и Python 3. Например, 3.5.7 , 3.7.2 и 3.8.0 являются частью основной версии Python 3.
  • MINOR — эти выпуски содержат новые возможности и функции. Например, 3.6.6 , 3.6.7 и 3.6.8 являются частью дополнительной версии Python 3.6.
  • MICRO — Новые микроверсии содержат различные исправления ошибок и улучшения.

В выпусках для разработки есть дополнительные квалификаторы. Для получения дополнительной информации прочтите документацию Python «Цикл разработки» .

Проверка версии Python

Python предварительно установлен в большинстве дистрибутивов Linux и macOS. В Windows его необходимо скачать и установить.

Чтобы узнать, какая версия Python установлена в вашей системе, выполните команду python —version или python -V :

Команда напечатает версию Python по умолчанию, в данном случае 2.7.15 . Версия, установленная в вашей системе, может отличаться.

Версия Python по умолчанию будет использоваться всеми сценариями, в которых /usr/bin/python установлен в качестве интерпретатора в строке сценария shebang .

В некоторых дистрибутивах Linux одновременно установлено несколько версий Python. Обычно двоичный файл Python 3 называется python3 , а двоичный файл Python 2 называется python или python2 , но это может быть не всегда.

Вы можете проверить, установлен ли у вас Python 3, набрав:

Поддержка Python 2 заканчивается в 2020 году. Python 3 — это настоящее и будущее языка.

На момент написания этой статьи последним основным выпуском Python была версия 3.8.x. Скорее всего, в вашей системе установлена более старая версия Python 3.

Если вы хотите установить последнюю версию Python, процедура зависит от используемой вами операционной системы.

Программная проверка версии Python

Python 2 и Python 3 принципиально разные. Код, написанный на Python 2.x, может не работать в Python 3.x.

Модуль sys , доступный во всех версиях Python, предоставляет системные параметры и функции. sys.version_info позволяет определить версию Python, установленную в системе. Это кортеж , который содержит пять номеров версий: major , minor , micro , releaselevel и serial .

Допустим, у вас есть сценарий, для которого требуется Python версии не ниже 3.5, и вы хотите проверить, соответствует ли система требованиям. Вы можете сделать это, просто проверив major и minor версии:

Если вы запустите скрипт с использованием Python версии ниже 3.5, он выдаст следующий результат:

Чтобы написать код Python, работающий как под Python 3, так и под Python 2, используйте модуль future . Он позволяет запускать код, совместимый с Python 3.x, под Python 2.

Выводы

Узнать, какая версия Python установлена в вашей системе, очень просто, просто введите python —version .

Как узнать версию Python в Linux Ubuntu?

Как посмотреть версию Python в терминале Linux?

Версия интерпретатора Python выводится в терминале командой

Однако, надо иметь в виду, что в современных дистрибутивах Ubuntu (и не только) присутствуют сразу две версии интерпретатора — Python 2 и Python 3. Указанная выше команда вызовет Python 2. Чтобы вызвать Python 3, команда должна быть другой:

Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.6.16.43501

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

How to Check Python Version in Linux, Mac, & Windows

Python is a popular programming language. Like many other programming languages, there can be several different versions organized by release date. Certain applications may require a specific version of Python.

In this tutorial, learn how to check the Python version on Windows, Linux, or macOS systems.

tutorial on how to check Python version.

Access to a command-line/terminal window:

  • Linux: Ctrl-Alt-T, Ctrl-Alt-F2
  • Windows: Win+R > type powershell > Enter/OK
  • MacOS: Finder > Applications > Utilities > Terminal

There are different versions of Python, but the two most popular ones are Python 2.7.x and Python 3.7.x. The x stands for the revision level and could change as new releases come out.

When looking at the version number, there are usually three digits to read:

  1. the major version
  2. the minor version
  3. the micro version

While major releases are not fully compatible, minor releases generally are. Version 3.6.1 should be compatible with 3.7.1 for example. The final digit signifies the latest patches and updates.

Python 2.7 and 3.7 are different applications. Software that’s written in one version often will not work correctly in another version. When using Python, it is essential to know which version an application requires, and which version you have.

Python 2 will stop publishing security updates and patches after 2020. They extended the deadline because of the large number of developers using Python 2.7. Python 3 includes a 2 to 3 utility that helps translate Python 2 code into Python 3.

How to Check Python Version in Linux

Most modern Linux distributions come with Python pre-installed.

To check the version installed, open a terminal window and entering the following:

python version linux

How to Check Python Version in Windows

Most out-of-the-box Windows installations do not come with Python pre-installed. However, it is always a good idea to check.

Open Windows Powershell, and enter the following:

If you have Python installed, it will report the version number.

check python version windows

Alternately, use the Windows Search function to see which version of Python you have:

Press the Windows key to start a search, then type Python. The system will return any results that match. Most likely a match will show something similar to:

This defines which major and minor revision (3.x or 2.x) you are using.

How to Check Python Version in MacOS

If using a MacOS, check the Python version by entering the following command in the terminal:

The system will report the version.

check python version macos

Note: In some cases, this will return a screen full of information. If that happens, just scan through the file locations for the word python with a number after it. That number is the version.

Checking a System with Multiple Versions of Python

Python2 and Python3 are different programs. Many programs upgrade from the older version to the newer one. However, Python 2.7.x installations can be run separately from the Python 3.7.x version on the same system.

Python 3 is not entirely backward compatible.

To check for Python 2.7.x:

To check the version of Python 3 software:

Most systems differentiate Python 2 as python and Python 3 as python3. If you do not have Python 2, your system may use the python command in place of python3 .

Note: Python does not have a built-in upgrade system. You’ll need to download the latest version and install it.

How to Check Python Version in Script

When writing an application, it is helpful to have the software check the version of Python before it runs to prevent crashes and incompatibilities.

Use the following code snippet to check for the correct version of Python:

When this script runs, it will test to see if Python 3.6 is installed on the system. If not, it will send a notification and displays the current Python version.

Note: One of the common issues in working with Python and datasets is missing data. Learn how to handle missing data in Python.

You should now have a solid understanding of how to check for the version of Python installed in several different operating systems. Python is a powerful programming language, thus it’s important to understand its different versions.

If you want to learn how to upgrade Python to a newer version on Wondows, macOs, and Linux, check our article how to upgrade Python to 3.9.

What version of Python do I have?

sigdelsanjog's user avatar

You can use python -V (et al.) to show you the version of Python that the python command resolves to. If that’s all you need, you’re done. But to see every version of python in your system takes a bit more.

In Ubuntu we can check the resolution with readlink -f $(which python) . In default cases in 14.04 this will simply point to /usr/bin/python2.7 .

We can chain this in to show the version of that version of Python:

But this is still only telling us what our current python resolution is. If we were in a Virtualenv (a common Python stack management system) python might resolve to a different version:

This is real output.

The fact is there could be hundreds of different versions of Python secreted around your system, either on paths that are contextually added, or living under different binary names (like python3 ).

If we assume that a Python binary is always going to be called python<something> and be a binary file, we can just search the entire system for files that match those criteria:

It’s obviously a pretty hideous command but this is again real output and it seems to have done a fairly thorough job.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *