Как посмотреть все библиотеки в python
Перейти к содержимому

Как посмотреть все библиотеки в python

  • автор:

 

pip list#

Packages are listed in a case-insensitive sorted order.

Options#

List outdated packages

List uptodate packages

List editable projects.

If in a virtualenv that has global access, do not list globally-installed packages.

Only output packages installed in user-site.

Restrict to the specified installation path for listing packages (can be used multiple times).

Include pre-release and development versions. By default, pip only finds stable versions.

Select the output format among: columns (default), freeze, or json

List packages that are not dependencies of installed packages.

Exclude editable package from output.

Include editable package from output.

Exclude specified package from the output

Base URL of the Python Package Index (default https://pypi.org/simple). This should point to a repository compliant with PEP 503 (the simple repository API) or a local directory laid out in the same format.

Extra URLs of package indexes to use in addition to —index-url. Should follow the same rules as —index-url.

How do I get a list of locally installed Python modules?

How do I get a list of Python modules installed on my computer?

Mateen Ulhaq's user avatar

Léo Léopold Hertz 준영's user avatar

33 Answers 33

in a Python shell/prompt.

Solution

Do not use with pip > 10.0!

My 50 cents for getting a pip freeze -like list from a Python script:

As a (too long) one liner:

Scope

This solution applies to the system scope or to a virtual environment scope, and covers packages installed by setuptools , pip and (god forbid) easy_install .

My use case

I added the result of this call to my flask server, so when I call it with http://example.com/exampleServer/environment I get the list of packages installed on the server’s virtualenv. It makes debugging a whole lot easier.

Caveats

I have noticed a strange behaviour of this technique — when the Python interpreter is invoked in the same directory as a setup.py file, it does not list the package installed by setup.py .

Steps to reproduce:

We have behave’s setup.py in /tmp/behave :

Install the python package from the git repo

If we run the aforementioned solution from /tmp

If we run the aforementioned solution from /tmp/behave

behave==1.2.5a1 is missing from the second example, because the working directory contains behave ‘s setup.py file.

I could not find any reference to this issue in the documentation. Perhaps I shall open a bug for it.

Adam Matan's user avatar

Now, these methods I tried myself, and I got exactly what was advertised: All the modules.

Alas, really you don’t care much about the stdlib, you know what you get with a python install.

Really, I want the stuff that I installed.

What actually, surprisingly, worked just fine was:

I say «surprisingly» because the package install tool is the exact place one would expect to find this functionality, although not under the name ‘freeze’ but python packaging is so weird, that I am flabbergasted that this tool makes sense. Pip 0.8.2, Python 2.7.

chiggsy's user avatar

Since pip version 1.3, you’ve got access to:

Which seems to be syntactic sugar for «pip freeze». It will list all of the modules particular to your installation or virtualenv, along with their version numbers. Unfortunately it does not display the current version number of any module, nor does it wash your dishes or shine your shoes.

In ipython you can type » import Tab «.

In the standard Python interpreter, you can type » help(‘modules’) «.

At the command-line, you can use pydoc modules .

johnsyweb's user avatar

I just use this to see currently used modules:

which shows all modules running on your python.

For all built-in modules use:

Which is a dict containing all modules and import objects.

In normal shell just use

As of pip 10, the accepted answer will no longer work. The development team has removed access to the get_installed_distributions routine. There is an alternate function in the setuptools for doing the same thing. Here is an alternate version that works with pip 10:

Please let me know if it will or won’t work in previous versions of pip, too.

If we need to list the installed packages in the Python shell, we can use the help command as follows

Sadheesh's user avatar

Works Regardless of Pip Version

Run the following in your python editor or IPython:

Read other answers and pulled together this combo, which is quickest and easiest inside Python.

Find the specific Packages

Conveniently you can then get items from your dict easily, i.e.

Using Pip List Well

!pip list will run inside your jupyter notebook if working there, simplifying the ‘quick check’ Combine with other utilities like grep(if you have installed) pip list | grep pandas will get you your current pandas version for example

jabberwocky's user avatar

I normally use pip list to get a list of packages (with version).

This works in a virtual environment too, of course. To show what’s installed in only the virtual environment (not global packages), use pip list —local .

Here’s documentation showing all the available pip list options, with several good examples.

James's user avatar

This will help

In terminal or IPython, type:

Abdullah Akhtar's user avatar

Amit Gupta's user avatar

Very simple searching using pkgutil.iter_modules

on windows, Enter this in cmd

 

Léo Léopold Hertz 준영's user avatar

I ran into a custom installed python 2.7 on OS X. It required X11 to list modules installed (both using help and pydoc).

To be able to list all modules without installing X11 I ran pydoc as http-server, i.e.:

Then it’s possible to direct Safari to http://localhost:12345/ to see all modules.

This solution is primary based on modules importlib and pkgutil and work with CPython 3.4 and CPython 3.5, but has no support for the CPython 2.

Explanation

  1. sys.builtin_module_names — names all built-in modules (look my answer here)
  2. pkgutil.iter_modules() — returns an information about all available modules
  3. importlib.util.find_spec() — returns an information about importing module, if exists
  4. BuiltinImporter — an importer for built-in modules (docs)
  5. SourceFileLoader — an importer for a standard Python module (by default has extension *.py) (docs)
  6. ExtensionFileLoader — an importer for modules as shared library (written on the C or C++)

Full code

Usage

For the CPython3.5 (truncated)

For the CPython3.4 (truncated)

Warning: Adam Matan discourages this use in pip > 10.0. Also, read @sinoroc’s comment below

This was inspired by Adam Matan’s answer (the accepted one):

which then prints out a table in the form of

which lets you then easily discern which packages you installed with and without sudo .

A note aside: I’ve noticed that when I install a packet once via sudo and once without, one takes precedence so that the other one isn’t being listed (only one location is shown). I believe that only the one in the local directory is then listed. This could be improved.

Daniel F's user avatar

In case you have an anaconda python distribution installed, you could also use

in addition to solutions described above.

Aside from using pip freeze I have been installing yolk in my virtual environments.

Tomasz Jakub Rup's user avatar

  1. to get all available modules, run sys.modules
  2. to get all installed modules (read: installed by pip ), you may look at pip.get_installed_distributions()

For the second purpose, example code:

pip freeze does it all finding packages however one can simply write the following command to list all paths where python packages are.

Pavan Gupta's user avatar

There are many way to skin a cat.

The most simple way is to use the pydoc function directly from the shell with:
pydoc modules

But for more information use the tool called pip-date that also tell you the installation dates.
pip install pip-date

enter image description here

I’m comparing five methods to retrieve installed "modules", all of which I’ve seen in this thread

iter_modules help("modules") builtin_module_names pip list working_set
Includes distributions ✔️ ✔️
Includes modules (No built-in) ✔️ ✔️
Includes built-in modules ✔️ ✔️
Includes frozen ✔️ ✔️
Includes venv ✔️ ✔️ ✔️ ✔️
Includes global ✔️ ✔️ ✔️ ✔️
Includes editable installs ✔️ ✔️ ✔️ ✔️
Includes PyCharm helpers ✔️
Lowers capital letters ✔️
Time taken (665 modules total) 53.7 msec 1.03 sec 577 nsec 284 msec 36.2 usec

Summary

  • pip list and working_set are for distributions, not modules.
  • iter_modules and help("modules") are very similar, the biggest difference is that iter_modules doesn’t include built-in.
  • pip list and working_set are very similar, only difference is that working_set lowers all capital letters.
  • Built-in modules are only included by help("modules") and builtin_module_names .

Related caveats

  • Distributions, packages, and modules often have identical names making it easy to mistake one for the other.
  • importlib.util.find_spec is for modules and is case-sensitive.
  • sys.modules only lists imported modules.

Distributions

I’m saying distribution instead of package because I think it will reduce misunderstandings. A distribution/package can have multiple packages/modules inside it.

An installed distribution is not always importable by the same name. For example pip install Pillow is imported with import PIL . Sometimes a distribution even makes multiple modules importable.

Где хранятся модули в Python?

Python_Deep_6.11-5020-3e1392.png

Система модулей даёт возможность логически организовать код на Python. Кроме того, группирование в модули значительно облегчает сам процесс написания кода, плюс делает его более понятным. В этой статье поговорим, что такое модуль в Python, где он хранится и как обрабатывается.

Модуль в Python — это файл, в котором содержится код на Python. Любой модуль в Python может включать в себя переменные, объявления функций и классов. Вдобавок ко всемe, в модуле может содержаться исполняемый код.

Команда import в Python

Позволяет использовать любой файл Python в качестве модуля в другом файле. Синтаксис прост:

Как только Python-интерпретатор встречает команду import, он выполняет импорт модуля, если он есть в пути поиска Python. Что касается пути поиска Python, то речь идёт о списке директорий, в которых интерпретатор выполняет поиск перед загрузкой модуля. Посмотрите на пример кода при использовании модуля math:

Помните, что модуль загружается только один раз, вне зависимости от того, какое количество раз вы его импортировали. Таким образом исключается цикличное выполнение содержимого модуля.

Команда from . import

Команда from . import даёт возможность выполнить импорт не всего модуля целиком, а лишь конкретного его содержимого:

Обратите внимание, что выражение from . import не импортирует модуль полностью, а лишь предоставляет доступ к объектам, указанным нами.

Команда from . import *

Также в Python мы можем импортировать из модуля переменные, классы и функции за один раз. Чтобы это выполнить, применяется конструкция from . import *:

Использовать данную конструкцию нужно осторожно, ведь при импорте нескольких модулей можно запутаться в собственном коде.

Так где хранятся модули в Python?

При импорте модуля, интерпретатор Python пытается найти модуль в следующих местах: 1. Директория, где находится файл, в котором вызывается команда импорта. 2. Директория, определённая в консольной переменной PYTHONPATH (если модуль не найден с первого раза). 3. Путь, заданный по умолчанию (если модуль не найден в предыдущих двух случаях).

Что касается пути поиска, то он сохраняется в переменной path в системном модуле sys. А переменная sys.path включает в себя все 3 вышеописанных места поиска.

2-20219-5cca3e.png

Получаем список всех модулей Python

Чтобы получить полный список модулей, установленных на ПК, используют команду help(«modules») .

3-20219-a2b765.png

Создаём свой модуль в Python

Для создания собственного модуля в Python нужно сохранить ваш скрипт с расширением .py. После этого он станет доступным в любом другом файле. Давайте создадим 2 файла: module_1.py и module_2.py, а потом сохраним их в одной директории. В первом файле запишем:

А во втором вызовем функцию:

После выполнения кода 2-го файла получим:

Функция dir() в Python

Возвратит отсортированный список строк с содержанием всех имён, определенных в модуле.

4-20219-710929.png

Пакеты модулей в Python

Несколько файлов-модулей с кодом можно объединить в пакеты модулей. Пакет модулей — это директория, включающая в себя несколько отдельных файлов-скриптов.

Представьте, что у нас следующая структура:

В файле inside_file.py определена некоторая функция foo. В итоге, дабы получить доступ к этой функции, в файле my_file нужно выполнить:

Также нужно обратить внимание на то, есть ли внутри директории my_package файл init.py. Это может быть и пустой файл, сообщающий Python, что директория является пакетом модулей. В Python 3 включать файл init.py в пакет модулей уже не обязательно, но мы рекомендуем всё же делать это, чтобы обеспечить обратную совместимость.

Менеджер пакетов pip: разбираемся с установкой дополнительных библиотек в Python

Smartiqa Article

Ведь не все пакеты нужны в повседневной практике или отдельном проекте, да и места они занимают не мало. Для этих целей создан удаленный репозиторий модулей https://pypi.org/ , в котором на сегодня имеется более 260 тыс. проектов на все случаи практики программирования. Вам не обязательно создавать код с нуля, так как под многие задачи уже имеется соответствующий пакет.

Работа с этим хранилищем расширений осуществляется через команду pip . Имеется и другой установщик easy_install , но он применяется существенно реже. Таким образом, пакетный менеджер pip необходим для установки, обновления, удаления и управления модулями языка Python.

2. Подготовительные мероприятия

Как видно из ответа, на данном ПК используется python версии 3.8 и pip версии 20.2.3 .

В некоторых случаях (актуально для пользователей Linux или macOS ) требуется применять команду pip3 (если в результате выполнения pip определяет, что у вас установлен python версии 2 по умолчанию). Это связано с тем, что на *nix системах присутствуют сразу обе версии языка.

Также если на вашем компьютере имеется несколько версий языка Python (например, 3.6 , 3.8 , 3.9 ), то менеджер пакетов может применяться отдельно для каждой из них:

3. Установка и удаление пакетов

При разработке сложных проектов может понадобиться установка большого количества модулей. Постоянно их скачивать из репозитория PyPi трудоемко. Для этого разработан способ загрузки пакетов локально. Они могут находиться в архивах ( *.tar.gz ) или специальных файлах с расширением .whl . Это удобно и в том случае, если нет доступа в интернет у выбранной машины, и вы заранее создали пакет со всеми необходимыми библиотеками.

Для примера запакуем модуль numpy в «колесо» ( wheel ) и установим его оттуда.

Вначале мы создали специальный локальный пакет NumPy и поместили его в текущую папку (о чем свидетельствует точка). В директории создался файл numpy-1.19.2-cp38-cp38-win32.whl . На его основании даже без интернета мы легко сможем установить данную библиотеку. Команда «—no-index» говорит о том, чтобы мы не искали модуль в репозитории PyPi , а —find-links принудительно указывает место расположения пакета. Когда речь идет о сотне пакетов, это очень удобно. Правда для этого необходимо освоить еще один инструмент: набор зависимостей (о нем – следующий раздел).

Рассмотрим вопрос удаления модулей. Если требуется удалить один пакет, то делается это по аналогии с установкой:

Читайте также

4. Файлы требований для управления пакетами

Серьезные и многоуровневые приложения никогда не обходятся одной библиотекой. Даже когда вы устанавливали тот же NumPy , вы могли заметить, что помимо самого модуля скачивались дополнительные пакеты, которые мы не запрашивали. Естественно они необходимы для правильной работы NumPy . Но откуда известно, что они нужны?

 

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

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