Python list packages in module

pip list#

List installed packages, including editables. Packages are listed in a case-insensitive sorted order.

Options#

-o , —outdated # List outdated packages -u , —uptodate # List uptodate packages -e , —editable # List editable projects. -l , —local # If in a virtualenv that has global access, do not list globally-installed packages. —user # Only output packages installed in user-site. —path # Restrict to the specified installation path for listing packages (can be used multiple times). —pre # Include pre-release and development versions. By default, pip only finds stable versions. —format # Select the output format among: columns (default), freeze, or json. The ‘freeze’ format cannot be used with the —outdated option. —not-required # List packages that are not dependencies of installed packages. —exclude-editable # Exclude editable package from output. —include-editable # Include editable package from output. —exclude # Exclude specified package from the output -i , —index-url # 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-index-url # Extra URLs of package indexes to use in addition to —index-url. Should follow the same rules as —index-url. —no-index # Ignore package index (only looking at —find-links URLs instead). -f , —find-links # If a URL or path to an html file, then parse for links to archives such as sdist (.tar.gz) or wheel (.whl) files. If a local path or file:// URL that’s a directory, then look for archives in the directory listing. Links to VCS project URLs are not supported.

Читайте также:  Python graph shortest path

Examples#

$ python -m pip list Package Version ------- ------- docopt 0.6.2 idlex 1.13 jedi 0.9.0 
C:\> py -m pip list Package Version ------- ------- docopt 0.6.2 idlex 1.13 jedi 0.9.0 
$ python -m pip list --outdated --format columns Package Version Latest Type ---------- ------- ------ ----- retry 0.8.1 0.9.1 wheel setuptools 20.6.7 21.0.0 wheel 
C:\> py -m pip list --outdated --format columns Package Version Latest Type ---------- ------- ------ ----- retry 0.8.1 0.9.1 wheel setuptools 20.6.7 21.0.0 wheel 
$ python -m pip list --outdated --not-required Package Version Latest Type -------- ------- ------ ----- docutils 0.14 0.17.1 wheel 
C:\> py -m pip list --outdated --not-required Package Version Latest Type -------- ------- ------ ----- docutils 0.14 0.17.1 wheel 
$ python -m pip list --format=json [, , . 
C:\> py -m pip list --format=json [, , . 
$ python -m pip list --format=freeze colorama==0.3.7 docopt==0.6.2 idlex==1.13 jedi==0.9.0 
C:\> py -m pip list --format=freeze colorama==0.3.7 docopt==0.6.2 idlex==1.13 jedi==0.9.0 

When some packages are installed in editable mode, pip list outputs an additional column that shows the directory where the editable project is located (i.e. the directory that contains the pyproject.toml or setup.py file).

$ python -m pip list Package Version Editable project location ---------------- -------- ------------------------------------- pip 21.2.4 pip-test-package 0.1.1 /home/you/.venv/src/pip-test-package setuptools 57.4.0 wheel 0.36.2 
C:\> py -m pip list Package Version Editable project location ---------------- -------- ---------------------------------------- pip 21.2.4 pip-test-package 0.1.1 C:\Users\You\.venv\src\pip-test-package setuptools 57.4.0 wheel 0.36.2 

The json format outputs an additional editable_project_location field.

$ python -m pip list --format=json | python -m json.tool [   "name": "pip", "version": "21.2.4", >,   "name": "pip-test-package", "version": "0.1.1", "editable_project_location": "/home/you/.venv/src/pip-test-package" >,   "name": "setuptools", "version": "57.4.0" >,   "name": "wheel", "version": "0.36.2" > ] 
C:\> py -m pip list --format=json | py -m json.tool [   "name": "pip", "version": "21.2.4", >,   "name": "pip-test-package", "version": "0.1.1", "editable_project_location": "C:\Users\You\.venv\src\pip-test-package" >,   "name": "setuptools", "version": "57.4.0" >,   "name": "wheel", "version": "0.36.2" > ] 

Contrary to the freeze command, pip list —format=freeze will not report editable install information, but the version of the package at the time it was installed.

Источник

How to find which Python modules are being imported from a package?

A file containing Python code, definitions of statements, functions, or classes is known as a module. A module with the name «module» that we will construct is a file named module.py.

To break down complex programmes into smaller, easier-to-understand parts, we use modules. Code reuse is another benefit of modules.

In this article, we will discuss various ways to find which Python modules are being imported from a package.

Using List Comprehension

To iterate over each element in the Python list, a list comprehension is made out of brackets carrying the expression, which is then run for each element.

Python List comprehension offers a much shorter syntax for creating a new list from the elements of an existing list.

Example

The following example returns all imported local module names by default in an unsorted list using the sys library with List Comprenehsion.

Using __name__ (also known as a dunder), this code iterates through sys.modules.values() to check if an item is a locally scoped module. If so, ‘output’ is saved with the module name. For readability, this code arranges the ‘output’ variable and saves it back to itself. List formatted output of these ‘output’ is sent to the terminal.

import sys output = [module.__name__ for module in sys.modules.values() if module] output = sorted(output) print('The list of imported Python modules are :',output)

Output

Following is an output of the above code −

The list of imported Python modules are : ['__main__', '_bootlocale', '_codecs', '_collections', '_functools', '_heapq', '_imp', '_locale', '_operator', '_signal', '_sitebuiltins', '_stat', '_sysconfigdata_m_linux_x86_64-linux-gnu', '_thread', '_warnings', '_weakref', '_weakrefset', 'abc', 'builtins', 'codecs', 'collections', 'collections.abc', 'collections.abc', 'contextlib', 'encodings', 'encodings.aliases', 'encodings.latin_1', 'encodings.utf_8', 'errno', 'functools', 'genericpath', 'heapq', 'importlib', 'importlib._bootstrap', 'importlib._bootstrap', 'importlib._bootstrap_external', 'importlib._bootstrap_external', 'importlib.abc', 'importlib.machinery', 'importlib.util', 'io', 'io', 'itertools', 'keyword', 'marshal', 'mpl_toolkits', 'operator', 'os', 'posix', 'posixpath', 'posixpath', 'reprlib', 'site', 'stat', 'sys', 'sysconfig', 'types', 'warnings', 'weakref', 'zipimport']

Using pip freeze command

This function shows a list of all names and versions of imported global modules, by default arranged alphabetically.

Example

Enter the below command by opening the terminal window in an IDE. In order to execute, press the Enter key −

Output

The terminal receives the output −

aspose-cells==22.7.0 click==8.1.3 cloudpickle==2.1.0 colorama==0.4.5 dask==2022.7.0 et-xmlfile==1.1.0 fsspec==2022.5.0 genno==1.11.0 ixmp==3.5.0 JPype1==1.4.0 llvmlite==0.38.1 locket==1.0.0 message-ix==3.5.0 modcall==0.1.0 mysql-connector-python==8.0.29 namespace==0.1.4 native==0.0.0.0a0.dev20210615 numba==0.55.2 numpy==1.22.4 openpyxl==3.0.10 packaging==21.3 pandas==1.4.3 partd==1.2.0 Pint==0.19.2 protobuf==4.21.2 psycopg2==2.9.3 pycparser==2.21 pyparsing==3.0.9 python-dateutil==2.8.2 python-dotenv==0.20.0 python-magic==0.4.27 pytz==2022.1 PyYAML==6.0 scipy==1.9.1 six==1.16.0 sparse==0.13.0 toolz==0.12.0 walk==0.3.5 workbook==1.1 xarray==2022.3.0 xlrd==2.0.1 xlutils==2.0.0 xlwt==1.3.0

Using dir() method

The dir() function returns all of the given object’s properties and methods, but not their related values. This function will even return built-in attributes that are the default for all objects.

Example

The dir() method is used in the following example to return a sorted list of all local module names −

module = dir() print('The list of imported Python modules are :',module)

Output

The output shown below demonstrate that this script only shows names relevant to our local scope −

The list of imported Python modules are : ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']

Using inspect.getmember() and a Lambda

A number of helpful functions are offered by the inspect module to help in gathering data on active objects such modules, classes, methods, functions, tracebacks, frame objects, and code objects. It can assist you in examining a class’s contents, retrieving a method’s source code, extracting and formatting a function’s argument list, or gathering all the data required to display a detailed traceback, among other things.

An anonymous, short function is known as a lambda. Although a lambda function can have only one expression, it can have any number of arguments.

Example

The following example returns the imported local modules in a sorted format using inspect.getmember() and a Lambda.

The names of the imported local modules and where they are located on the system are returned by this code as an iterable object. This is iterated through and printed as one line using a for loop.

import inspect import os modules = inspect.getmembers(os) results = filter(lambda m: inspect.ismodule(m[1]), modules) for o in results: print('The list of imported Python modules are :',o)

Output

Following is an output of the above code −

The list of imported Python modules are : ('abc', ) The list of imported Python modules are : ('errno', ) The list of imported Python modules are : ('path', ) The list of imported Python modules are : ('st', ) The list of imported Python modules are : ('sys', )

Using sys module

The sys.modules dict can be used to discover all the Python modules from a specific package that are being utilised by an application. A dictionary that links module names to modules is called sys.modules. To see imported modules, you can look at its keys.

Example

Following is an example to find the imported modules from a package using sys module

from datetime import datetime import sys print (sys.modules.keys())

Output

Following is an output of the above code −

dict_keys(['builtins', 'sys', '_frozen_importlib', '_imp', '_warnings', '_thread', '_weakref', '_frozen_importlib_external', '_io', 'marshal', 'posix', 'zipimport', 'encodings', 'codecs', '_codecs', 'encodings.aliases', 'encodings.utf_8', '_signal', '__main__', 'encodings.latin_1', 'io', 'abc', '_weakrefset', '_bootlocale', '_locale', 'site', 'os', 'errno', 'stat', '_stat', 'posixpath', 'genericpath', 'os.path', '_collections_abc', '_sitebuiltins', 'sysconfig', '_sysconfigdata_m_linux_x86_64-linux-gnu', 'types', 'functools', '_functools', 'collections', 'operator', '_operator', 'keyword', 'heapq', '_heapq', 'itertools', 'reprlib', '_collections', 'weakref', 'collections.abc', 'importlib', 'importlib._bootstrap', 'importlib._bootstrap_external', 'warnings', 'importlib.util', 'importlib.abc', 'importlib.machinery', 'contextlib', 'mpl_toolkits', 'datetime', 'time', 'math', '_datetime'])

Источник

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