在 python 中,导入模块后,有没有办法找到它是从哪个物理文件加载的?

use*_*108 1 python module loading package

我认为我的数学包中出现了问题,我想确保加载正确的模块。如何检查 python 中加载模块的物理文件位置?

Bak*_*riu 5

使用__file__属性:

>>> import numpy
>>> numpy.__file__
'/usr/lib/python2.7/dist-packages/numpy/__init__.pyc'
Run Code Online (Sandbox Code Playgroud)

请注意,用 C 编写并静态链接到解释器的内置模块没有此属性:

>>> import math
>>> math.__file__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '__file__'
Run Code Online (Sandbox Code Playgroud)

获取文件路径的另一种方法是使用inspect.getfile. TypeError如果传递的对象是内置模块、类或函数,则会引发该错误。

另外,您应该避免使用与语言内​​置或标准库模块冲突的名称。因此,我建议您将math包重命名为其他名称,或者,如果它是像 之类的包的一部分mypackage.math,请避免直接导入它并使用mypackage.math它。