Узнать все версии 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 — это настоящее и будущее языка.

Читайте также:  Linux облако своими руками

На момент написания этой статьи последним основным выпуском 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 .

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

Источник

How to Check all the Python Versions Installed on Linux

How to Check all the Python Versions Installed on Linux 1

In this article, we will see how to check all the python versions installed on a Linux system. Many times you might have noticed that either knowingly or unknowingly you end up installed multiple python versions in your linux system. And some day you only realize this when you started getting certain strange messages on the output pointing different versions of python available in the System. Well, at that point of time you probably would like to know all the python versions installed on your System. While there are many ways to check this but here we will only see four methods that can be used in a linux system to detect all the python versions.

Читайте также:  Не грузится usb linux

How to Check all the Python Versions Installed on Linux 2

How to Check all the Python Versions Installed on Linux

Method 1: Using whereis command

The first method you can think of using is through whereis command which is easily available in almost all the linux distributions. So if you are looking for all the versions of python3 then you just need to run whereis python3 command and you will able to see all the python3 versions as shown below. This works great in almost all the linux systems.

cyberithub@ubuntu:~$ whereis python3 python3: /usr/bin/python3 /usr/bin/python3.8 /usr/bin/python3.9 /usr/lib/python3 /usr/lib/python3.8 /usr/lib/python3.9 /etc/python3 /etc/python3.8 /etc/python3.9 /usr/local/lib/python3.8 /usr/local/lib/python3.9 /usr/include/python3.8 /usr/share/python3 /usr/share/man/man1/python3.1.gz

Similarly, if you would like to check all the installed versions of python2 then you need to use whereis python2 command as shown below.

cyberithub@ubuntu:~$ whereis python2 python2: /usr/bin/python2.7 /usr/bin/python2 /usr/lib/python2.7 /etc/python2.7 /usr/local/lib/python2.7 /usr/share/man/man1/python2.1.gz

Method 2: Using ls command

The second method that I always love to use is through ls command. This command is also very easily available on almost all the linux distribution. Using this command, you just need to look for all the python binaries available under /usr/bin path to detect all the versions of python currently installed as shown below. You can check more about ls command on 16 Best ls command examples in Linux.

cyberithub@ubuntu:~$ ls -ls /usr/bin/python* 0 lrwxrwxrwx 1 root root 9 Mar 13 2020 /usr/bin/python2 -> python2.7 3580 -rwxr-xr-x 1 root root 3662032 Jul 1 2022 /usr/bin/python2.7 0 lrwxrwxrwx 1 root root 9 Nov 15 20:46 /usr/bin/python3 -> python3.8 5368 -rwxr-xr-x 1 root root 5494584 Nov 14 18:29 /usr/bin/python3.8 5668 -rwxr-xr-x 1 root root 5803968 Nov 23 2021 /usr/bin/python3.9 4 -rwxr-xr-x 1 root root 384 Mar 28 2020 /usr/bin/python3-futurize 4 -rwxr-xr-x 1 root root 388 Mar 28 2020 /usr/bin/python3-pasteurize

Method 3: Using compgen command

Another method that you can think of using is through compgen command. If this utility is available in your system then you need to simply run compgen -c python | grep -P ‘^python\d’ command to list out all the versions of python installed in the system.

cyberithub@ubuntu:~$ compgen -c python | grep -P '^python\d' python3-pasteurize python2.7 python2 python3 python3.8 python3-futurize python3.9 python3-pasteurize python2.7 python2 python3 python3.8 python3-futurize python3.9

Method 4: Using find command

The last method that I would advise to use is through find command. You can search and look for all different python symbolic link under /usr/bin path using find /usr/bin/python* ! -type l command as shown below. You can check more about find command on 40 Best Examples of Find Command in Linux.

cyberithub@ubuntu:~$ find /usr/bin/python* ! -type l /usr/bin/python2.7 /usr/bin/python3.8 /usr/bin/python3.9 /usr/bin/python3-futurize /usr/bin/python3-pasteurize

Источник

Читайте также:  Manjaro 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.

Источник

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