Проверить версию питона linux

What version of Python do I have?

@TejasKale Better to run ls /usr/bin/python* (or ls /usr/bin/*python* if you really want files with python anywhere in the name). That way, ls still formats its output for a terminal (and you get multiple columns and, with the default ls alias in Ubuntu, colorization).

9 Answers 9

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:

$ readlink -f $(which python) | xargs -I % sh -c 'echo -n "%: "; % -V' /usr/bin/python2.7: Python 2.7.6 

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:

$ readlink -f $(which python) | xargs -I % sh -c 'echo -n "%: "; % -V' /home/oli/venv/bin/python: Python 2.7.4 

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 and be a binary file, we can just search the entire system for files that match those criteria:

$ sudo find / -type f -executable -iname 'python*' -exec file -i '<>' \; | awk -F: '/x-executable; charset=binary/ ' | xargs readlink -f | sort -u | xargs -I % sh -c 'echo -n "%: "; % -V' /home/oli/venv/bin/python: Python 2.7.4 /media/ned/websites/venvold/bin/python: Python 2.7.4 /srv/chroot/precise_i386/usr/bin/python2.7: Python 2.7.3 /srv/chroot/trusty_i386/usr/bin/python2.7: Python 2.7.6 /srv/chroot/trusty_i386/usr/bin/python3.4: Python 3.4.0 /srv/chroot/trusty_i386/usr/bin/python3.4m: Python 3.4.0 /usr/bin/python2.7: Python 2.7.6 /usr/bin/python2.7-dbg: Python 2.7.6 /usr/bin/python3.4: Python 3.4.0 /usr/bin/python3.4dm: Python 3.4.0 /usr/bin/python3.4m: Python 3.4.0 /web/venvold/bin/python: Python 2.7.4 

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

Источник

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

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

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

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

Читайте также:  Rockstar social club linux

Управление версиями 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 версии:

import sys if not (sys.version_info.major == 3 and sys.version_info.minor >= 5): print("This script requires Python 3.5 or higher!") print("You are using Python <>.<>.".format(sys.version_info.major, sys.version_info.minor)) sys.exit(1) 

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

This script requires Python 3.5 or higher! You are using Python 2.7. 

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

Выводы

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

Не стесняйтесь оставлять комментарии, если у вас есть вопросы.

Читайте также:  Easy windows to linux

Источник

Check Your Python Version

Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.

Python reigns as one of the most popular programming languages, with a wide range of programs and developer tools relying on it. In fact, your system likely already has at least one version of Python installed.

Many tools and Python development libraries require a particular version of Python. Thus, you may want to know where you can find information on your installed Python version. This can help you make decisions about compatibility, upgrades, and more.

This tutorial shows you how to check your Python version, for both Python 2 and Python 3. Here, you can find the command line method as well as a Python script method for retrieving the current Python version.

How to Check the Python Version from the Command Line

The Python command comes with a command line option of —version that allows you to see your installed version.

It works just as straightforwardly as it sounds. Enter the following command from your command line, and you should get an output similar to the one shown below:

Python 2 vs Python 3

Some systems distinguish between Python 2 and Python 3 installations. In these cases, to check your version of Python 3, you need to use the command python3 instead of python .

In fact, some systems use the python3 command even when they do not have Python 2 installed alongside Python 3. In these cases, you only have the python3 command.

The command for checking the installed version of Python 3 remains otherwise the same — just use python3 with the —version option:

How to Check the Python Version from Python

You can also check your installed Python version from within Python itself. Using either a script or the Python shell, you can use one of the code snippets below to print your Python version.

Both options work equally well regardless of your system. The choice of which option to use really comes down to what format you want the output in.

Using sys

The sys module has a variable you can reference to get the current Python version. Below you can see an example of how the sys module’s version variable renders the current Python version. This code first imports the sys module then prints out the contents of the version variable:

3.8.10 (default, Jun 22 2022, 20:18:18) [GCC 9.4.0]

As you can see, the sys.version variable contains more information about your installed Python version than just the number. For that reason, sys is a good module to turn to when you want more verbose version information.

Using platform

The platform module includes a function that fetches the current version of Python. The example code below uses this function to print the current Python version number. It first imports the platform module; then, the python_version function returns the version number to the print function:

Читайте также:  Check proxy list linux

The output from the platform.python_version is more minimal compared to the sys module’s version variable. This makes the platform module more useful for cases when you only need the version number. For example, this method helps when you want to design a program to parse the Python version and act accordingly.

Conclusion

With that, you have everything you need for checking your current Python version. The steps above cover you whether you need to see the Python version from the command line or from within a Python script.

You can continue learning about Python with our collection of Python guides. We cover everything from fundamental Python concepts to building Python web applications.

More Information

You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

This page was originally published on Monday, August 15, 2022.

Источник

How to Check Your Python Version (Windows, macOS, Linux)

How to Check Your Python Version (Windows, macOS, Linux) Cover Image

In this tutorial, you’ll learn how to check your Python version in Windows, macOS, and Linux. You’ll learn how to check the version of Python using the command line and within a Python script itself. You’ll learn how to get the version number of the interpreter that your scripts will use.

Knowing how to do this is an important skill for any Python developer. For example, it can be an important skill in order to better troubleshoot your code. If your interpreter is set to a different version than you’re expecting (say, Python 2 versus Python 3), being able to identify the version of the interpreter can help troubleshoot your problems.

By the end of this tutorial, you’ll have learned:

  • How to check the Python version of your interpreter in Windows, Mac OS, and Linux
  • How the check the Python version while running your script
  • How to access the major, minor and micro versions of your Python version programmatically

How to Check Your Python Version

To check the version that your Python interpreter is running we can use a version command on the python command. Because accessing the command line prompt or terminal varies from system to system, this part of the tutorial is split across the different operating systems available to you.

Over the following sections, you’ll learn how to check your Python version using Windows 10, Windows 7, macOS, and Linux.

How to Check Your Python Version on Windows 10

In Windows 10, we can use the PowerShell to check the version of Python that we are running. In order to access the PowerShell, simply use the following steps:

Once the PowerShell is open you can access the Python version your interpreter is running by writing the commands shown below.

Источник

Оцените статью
Adblock
detector