📜  如何在Python定位特定模块?

📅  最后修改于: 2022-05-13 01:55:42.686000             🧑  作者: Mango

如何在Python定位特定模块?

在本文中,我们将看到如何在Python定位特定模块?定位模块意味着找到导入模块的目录。当我们导入一个模块时, Python解释器以下列方式搜索该模块:

  • 首先,它在当前目录中搜索模块。
  • 如果在当前目录中找不到该模块, Python将在 shell 变量 PYTHONPATH 中搜索每个目录。 PYTHONPATH 是一个环境变量,由目录列表组成。
  • 如果这也失败Python检查在安装Python的时间配置目录的安装相关的名单。

sys.path 包含当前目录的列表、PYTHONPATH 和依赖于安装的默认值。我们将在本文中讨论如何使用这种方法和其他方法来定位模块。

方法一:使用os模块

对于纯Python模块,我们可以通过 module_name.__file__ 来定位它的来源。这将返回模块的 .py 文件所在的位置。要获取目录,我们可以使用 os 模块中的 os.path.dirname() 方法。例如,如果我们想使用这种方法知道“随机”模块的位置,我们将在Python文件中键入以下内容

Python
# importing random module
import random
  
# importing the os module
import os
  
# storing the path of modules file 
# in variable file_path
file_path = random.__file__
  
# storing the directory in dir variable
dir = os.path.dirname(file_path)
  
# printing the directory
print(dir)


Python
# importing sys module
import sys
  
# importing sys.path
print(sys.path)


Python
# importing os module
import os
  
# printing help(os)
print(help(os))


Python
# importing random module
import inspect
  
# importing the os module
import os
  
# printing the file path of os module
print(inspect.getfile(os))


输出:



C;\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib

方法二:使用 sys.path

对于这种方法,我们将使用 sys 模块。 sys 模块的 sys.path 变量包含所有将在运行时搜索模块的目录。因此,通过了解这些目录,我们可以手动检查特定模块的位置。为了实现这一点,我们必须在Python shell 中编写以下内容:-

Python

# importing sys module
import sys
  
# importing sys.path
print(sys.path)

这将返回将在运行时搜索模块的所有目录的列表。

输出:

方法 3:使用 help(module_name)

在我们导入一些模块后的Python shell中,我们可以使用help(module_name)获取有关模块的各种信息。例如,如果我们想知道使用这种方法的模块 os 的位置,我们将在Python shell 中键入以下内容



Python

# importing os module
import os
  
# printing help(os)
print(help(os))

在各种信息下,我们会找到一个名为 FILE 的标题,其下方将显示模块的位置。

输出:

方法四:使用inspect模块

我们也可以使用Python的inspect模块来定位一个模块。我们将使用inspect模块的inspect.getfile()方法来获取路径。此方法将模块的名称作为参数并返回其路径。例如,如果我们要使用这种方法查找 os 模块的目录,我们将编写以下代码:

Python

# importing random module
import inspect
  
# importing the os module
import os
  
# printing the file path of os module
print(inspect.getfile(os))

输出: