Как проверить версии модулей Python

Часто возникает необходимость узнать версию установленного модуля Python, чтобы быть уверенным в его совместимости с другими компонентами проекта или для обеспечения корректной работы программы. К примеру, модуль numpy был установлен в проект с помощью инструмента pip :
И теперь необходимо узнать его версию.
Эта задача может быть решена несколькими способами, в зависимости от потребностей и предпочтений.
Использование командной строки
Самый простой способ проверить версию модуля Python — использовать командную строку. Следующая команда покажет версию установленного модуля:
В результате будет выведена информация о модуле, включая его версию.
Использование Python shell
Если требуется проверить версию модуля прямо во время выполнения программы, можно использовать Python shell. Для этого нужно импортировать модуль и вывести его атрибут __version__ . Вот пример для модуля numpy :
Эта команда выведет версию установленного модуля numpy .
Оба этих способа позволяют быстро и просто узнать версию установленного модуля Python. Выбор метода зависит от конкретной ситуации и предпочтений пользователя.
Python 3: Как узнать версию библиотеки Pandas, Numpy
Вариант 1. Узнаем версию библиотеки в скрипте Python
Для того, чтобы узнать версию библиотеки, необходимо вбить следующую команду (например для Pandas):
Пример для Numpy:
Вариант 2. Проверить с помощью pip менеджера пакетов
С помощью менеджера пакетов pip можно проверить версию установленных библиотек, для этого используются команды:
- pip list
- pip freeze
- pip show pandas
pip list
Выведет список установленных пакетов, включая редактируемые.
Пишем в консоли команду:
Результат:

pip freeze
Выводит установленные пакеты, которые ВЫ установили с помощью команды pip (или pipenv при ее использовании) в формате требований.
Вы можете запустить: pip freeze > requirements.txt на одной машине, а затем на другой машине (в чистой среде) произвести инсталляцию пакетов: pip install -r requirements.txt .
Таким образом вы получите идентичную среду с точно такими же установленными зависимостями, как и в исходной среде, в которой вы сгенерировал файл requirements.txt.
Результат:

pip show
Выводит информацию об одном или нескольких установленных пакетах.
Пример:
Результат:

Anaconda — conda list
Если вы используете Anaconda, то вы можете проверить список установленных пакетов в активной среде с помощью команды conda list .
How to Check Version of Installed Python Modules

One of the most useful features of Python is its huge collection of in-built modules. Modules make everything easier. Due to the availability of numerous python libraries, implementing python code using the in-built modules has increasingly become hassle-free.
But, when we are importing certain modules, we must ensure that they are up-to-date, or else they might raise unwanted errors. In order to write flawless code, we must ensure that the modules are at par with the latest python version in our system.
Checking the version of Python modules
The version of our installed python libraries can be checked and further updated using the pip module. There are many ways in which you can ensure that your system is up to date with the latest release version in order to avoid missing out on exciting new features.
Let us look at how we can check the versions of installed python modules.
Make sure your pip version is >= 1.3! If your pip is not updated, make sure you update it.
If you want to read more about python modules, read this awesome article on Introduction to Python Modules.
Method 1: using pip freeze
The pip freeze method lists all the installed packages and their versions in an alphabetical order.
Open your command prompt and run the following command:
Your output will look something like this:

Pip Freeze
Method 2: Using pip list
The pip list method also works in a similar manner. It will list all the python modules installed in your system followed by their versions that are locally available on your system.
Run the following code to see the entire list of the modules and their versions on your system.

Pip List
Method 3: Using pip show
Using pip show, we can determine the version of one specified module according to our needs. Lets look at how this can be done:
Run the following code in your command prompt: pip show numpy (OR ANY OTHER MODULE VERSION THAT YOU WANNA KNOW)
The output will e something as shown below:
To know more about PIP, check out: Python PIP – Package Manager.
Method 4: using package.__version__ function
This method can be used in the python shell to display the version of a particular library. We can implement this method as follows:
I have used numpy here, you can modify it according to your use. The output would be simply the version of numpy installed in your system.
Method 5: Using importlib from python
There is a python module called importlib(also called ,import library) which can be used to check the version of a particular module in our python script or terminal. The importlib package contains a function called metadata which is useful for extracting information about modules.
Before you use this package, make sure you have it in your system. If not, run pip install importlib in your command prompt in administrator mode as to maintain all PATH properly.
Now, we will look at how to use this package. I will run my code in the python shell.
I already had the DateTime module installed, that’s why I am using it to check the proper functionality of the importlib.metadata.version() . You can use whatever module you want to know the version of.
The output of the above code will be the version of your required module. In this case, 5.0 is the output that I got, because that version of DateTime exists locally.

Using __version__(method 4) followed by importlib(method 5)
Conclusion
In this tutorial, we have seen how to determine the versions of the installed python packages in our system. This can be done in five different ways and each of those methods are extremely easy to use.
The simple syntax of python is one of the biggest reasons why it is so popular. Besides the syntax, the huge collection of in-built functions and modules make programming in this language extremely efficient even at a large scale. Hence, it is important to keep all modules up-to-date so that we can maximize our productivity and make the best use of newly added features!
Find version of a Python library using pip list and grep
If you want to get the version of a Python library, you can use pip list . But a quicker way is to use pip list | grep package_name .
The grep command is used to search files that match a given string. Above is an example to get the version of your pandas library using pip list and grep
Related Posts






Page stats
Start date: 11-23-2020
Total number of subscribers: 3,190
Total number of posts: 806
Tips: To bookmark the posts you like, sign in then like the post you want to bookmark. You should see all posts you liked in the Recent Likes tab.