Проверить версию питона на линукс

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, установленную на машине пользователя.

Читайте также:  Linux mint второй экран

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

Читайте также:  Одно и многопоточность linux

Выводы

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

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

Источник

How to Check Your Python Version

Chances are you have heard about Python 2 and Python 3. Although they are two versions of the same language, they have different syntax; code written in Python 3 might not work in Python 2. So, let’s discover how you can check your Python version on the command line and in the script on Windows, macOS, and Linux systems.

Python is one of the most popular programming languages. With its simple syntax, high productivity, and amazing open-source libraries, Python can be used for just about anything.

However, you might have seen that some people use Python 2, while others prefer Python 3. The difference between these two versions is quite significant – it’s not just about fixing some bugs and adding a few new features. If the application is written in Python 2, you may not be able to run it using Python 3.

So, you should definitely know the version of Python installed on your computer. Let’s see how you can check the Python version. We’ll start with the command line.

Check Python Version: Command Line

You can easily check your Python version on the command line/terminal/shell. Let’s first recall how we can access the command line in different operating systems.

Windows

macOS

Linux

Then, for any of the operations systems above, you simply type python —version OR python -V, on the command line and press Enter . You’ll get a result like this:

python --version Python 3.8.3 python -V Python 3.8.3

Depending on your Python distribution, you may get more information in the result set. However, the number next to Python is the version number, which is what we are looking for. In this case, the full version number is 3.8.3.

Usually, we are interested in the major version – Python 2 or Python 3. This is indicated by the first number of the full version number. This number is 3 in our case, which means that we have Python 3 installed on our computer.

Starting from Python 3.6, you can also use python -VV (this is two Vs, not a W) to get more detailed information about your Python version:

python -VV Python 3.8.3 (default, Jul 2 2020, 17:30:36) [MSC v.1916 64 bit (AMD64)]

Check Python Version: Script

Sometimes you may want to check the version of Python when you are coding an application (i.e. inside the script). This is especially useful when you have multiple Python versions installed on your computer. To check which Python version is running, you can use either the sys or the platform module. The script will be the same for Windows, macOS, and Linux.

Читайте также:  Linux посмотреть трафик сети

To check the Python version using the sys module, write:

import sys print (sys.version)
# 3.8.3 (default, Jul 2 2020, 17:30:36) [MSC v.1916 64 bit (AMD64)]

To check the Python version using the platform module, use the following code:

import platform print(platform.python_version())

The output will be as follows:

Both code snippets output the Python version in the string format. If necessary, you can also get the version number in the tuple format. The tuple will contain five components: major, minor, micro, release level, and serial:

print (sys.version_info) # sys.version_info(major=3, minor=8, micro=3, releaselevel='final', serial=0)

Of course, you can easily obtain the individual components of this tuple using an index (e.g. sys.version_info[0] ) or a name (e.g. sys.version_info.major ).

Pretty simple, right? No wonder Python is so popular.

Python 2 or Python 3?

Now we know how to check the Python version. But what’s the difference between the two versions?

Python 2 is an older version that was actively used in software development and IT operations (DevOps). However, it is no longer under development and has been discontinued starting from January 1, 2020. This implies that any bugs or security problems discovered in Python 2 are no longer being addressed by Python developers. Python’s volunteer developers advise that people using Python 2 move to Python 3 as soon as possible.

Python 3 was first introduced in 2008. It’s syntax and behavior is quite different from Python 2, but it’s generally believed that Python 3 is simpler and easier to understand.

As Python 2 is no longer supported, you should definitely choose Python 3 if you are writing a new application or just starting to learn Python. The only reason to learn Python 2 is if your company’s code is written in Python 2 and you need to work with it. This shouldn’t be often the case, especially once Python 2 has been discontinued for a while.

Time to Practice Python!

Do you want to learn Python 3? Join the track Learning Programming with Python on LearnPython.com, where you will be introduced to the fundamentals of programming – not just in theory but with over 400 interactive coding challenges.

The track starts with Python Basics: Part 1, a course that teaches students how to create the simplest Python applications. This course (and the track itself) are aimed at students with no prior IT background. If you are already familiar with Python’s basics, join one of the advanced courses on LearnPython.com and learn how to work with strings, JSON files, and CSV files in Python.

Professionals across different industries enjoy the benefits of this simple and effective programming language. You can join them very soon! It doesn’t take much time to become proficient in Python, especially if you plan your studying activities appropriately.

Thanks for reading, and happy learning!

Источник

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