Python check which modules imported

modulefinder — Find modules used by a script¶

This module provides a ModuleFinder class that can be used to determine the set of modules imported by a script. modulefinder.py can also be run as a script, giving the filename of a Python script as its argument, after which a report of the imported modules will be printed.

modulefinder. AddPackagePath ( pkg_name , path ) ¶

Record that the package named pkg_name can be found in the specified path.

modulefinder. ReplacePackage ( oldname , newname ) ¶

Allows specifying that the module named oldname is in fact the package named newname.

class modulefinder. ModuleFinder ( path = None , debug = 0 , excludes = [] , replace_paths = [] ) ¶

This class provides run_script() and report() methods to determine the set of modules imported by a script. path can be a list of directories to search for modules; if not specified, sys.path is used. debug sets the debugging level; higher values make the class print debugging messages about what it’s doing. excludes is a list of module names to exclude from the analysis. replace_paths is a list of (oldpath, newpath) tuples that will be replaced in module paths.

Print a report to standard output that lists the modules imported by the script and their paths, as well as modules that are missing or seem to be missing.

Читайте также:  Java кириллица в латиницу

Analyze the contents of the pathname file, which must contain Python code.

A dictionary mapping module names to modules. See Example usage of ModuleFinder .

Example usage of ModuleFinder ¶

The script that is going to get analyzed later on (bacon.py):

import re, itertools try: import baconhameggs except ImportError: pass try: import guido.python.ham except ImportError: pass 

The script that will output the report of bacon.py:

from modulefinder import ModuleFinder finder = ModuleFinder() finder.run_script('bacon.py') print('Loaded modules:') for name, mod in finder.modules.items(): print('%s: ' % name, end='') print(','.join(list(mod.globalnames.keys())[:3])) print('-'*50) print('Modules not imported:') print('\n'.join(finder.badmodules.keys())) 

Sample output (may vary depending on the architecture):

Loaded modules: _types: copyreg: _inverted_registry,_slotnames,__all__ re._compiler: isstring,_sre,_optimize_unicode _sre: re._constants: REPEAT_ONE,makedict,AT_END_LINE sys: re: __module__,finditer,_expand itertools: __main__: re,itertools,baconhameggs re._parser: _PATTERNENDERS,SRE_FLAG_UNICODE array: types: __module__,IntType,TypeType --------------------------------------------------- Modules not imported: guido.python.ham baconhameggs 

Источник

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'])

Источник

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