使用__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它。