如何查詢從包中匯入了哪些 Python 模組?


包含 Python 程式碼、語句、函式或類定義的檔案稱為模組。我們將建立的名為“module”的模組是一個名為 module.py 的檔案。

為了將複雜的程式分解成更小、更容易理解的部分,我們使用模組。程式碼重用是模組的另一個好處。

在本文中,我們將討論查詢從包中匯入了哪些 Python 模組的各種方法。

使用列表推導式

為了迭代 Python 列表中的每個元素,列表推導式由包含表示式的方括號組成,然後對每個元素執行該表示式。

Python 列表推導式提供了一種更短的語法,用於從現有列表的元素建立新列表。

示例

以下示例使用 sys 庫和列表推導式,預設情況下以未排序列表的形式返回所有匯入的本地模組名稱。

使用 `__name__`(也稱為 dunder),此程式碼迭代 `sys.modules.values()` 以檢查專案是否為本地作用域模組。如果是,則將模組名稱與 ‘output’ 儲存。為提高可讀性,此程式碼對 ‘output’ 變數進行排序並將其儲存回自身。這些 ‘output’ 的列表格式輸出將傳送到終端。

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)

輸出

以下是上述程式碼的輸出:

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

使用 pip freeze 命令

此函式顯示所有匯入的全域性模組的名稱和版本的列表,預設情況下按字母順序排列。

示例

在 IDE 中開啟終端視窗,輸入以下命令。按 Enter 鍵執行:

C:\Users\Lenovo>pip freeze

輸出

終端接收輸出:

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

使用 dir() 方法

dir() 函式返回給定物件的所有屬性和方法,但不返回其相關值。此函式甚至會返回所有物件的預設內建屬性。

示例

以下示例使用 dir() 方法返回所有本地模組名稱的排序列表:

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

輸出

以下輸出表明此指令碼僅顯示與我們的本地作用域相關的名稱:

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

使用 inspect.getmember() 和 lambda 函式

inspect 模組提供許多有用的函式,有助於收集有關活動物件(如模組、類、方法、函式、回溯、幀物件和程式碼物件)的資料。它可以幫助您檢查類的內容、檢索方法的原始碼、提取和格式化函式的引數列表,或收集顯示詳細回溯所需的所有資料,等等。

匿名、簡短的函式稱為 lambda 函式。雖然 lambda 函式只能有一個表示式,但它可以具有任意數量的引數。

示例

以下示例使用 inspect.getmember() 和 lambda 函式返回排序格式的匯入本地模組。

此程式碼將匯入的本地模組的名稱及其在系統中的位置作為可迭代物件返回。使用 for 迴圈對其進行迭代並逐行列印。

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)

輸出

以下是上述程式碼的輸出:

The list of imported Python modules are : ('abc', <module 'abc' from '/usr/lib64/python3.6/abc.py'>)
The list of imported Python modules are : ('errno', <module 'errno' (built-in)>)
The list of imported Python modules are : ('path', <module 'posixpath' from '/usr/lib64/python3.6/posixpath.py'>)
The list of imported Python modules are : ('st', <module 'stat' from '/usr/lib64/python3.6/stat.py'>)
The list of imported Python modules are : ('sys', <module 'sys' (built-in)>)

使用 sys 模組

可以使用 `sys.modules` 字典來查詢應用程式正在使用的特定包中的所有 Python 模組。`sys.modules` 是一個將模組名稱與模組關聯起來的字典。要檢視匯入的模組,可以檢視其鍵。

示例

以下是一個使用 sys 模組查詢從包中匯入的模組的示例:

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

輸出

以下是上述程式碼的輸出:

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

更新於:2022年11月23日

11K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.