9

我得到了包含声明的模块名称os.path.isfileJedi lib 给了我genericpath(没有文件路径)。现在我想用这个genericpath模块获取 PY 文件的完整文件名。例如“C:\Py27\Lib\genericpath.py”。我该怎么做?绝地做不到?

4

4 回答 4

13

您可以检查的值__file__

>>> import genericpath
>>> genericpath.__file__
 '/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/genericpath.pyc'
于 2013-08-30T18:48:16.967 回答
11

如果__file__不起作用,请以正确的方式进行操作 - 使用inspect

>>> import somemodule
>>> import inspect
>>> inspect.getfile(somemodule)
'/usr/lib64/python2.7/somemodule.pyc'
于 2015-12-03T07:46:12.987 回答
5

像这样:

>>> import re
>>> re.__file__
'/usr/lib/python2.7/re.pyc'

对于不属于 Python 核心的包,您还可以使用__path__

>>> import requests
>>> requests.__file__
'/usr/local/lib/python2.7/dist-packages/requests-1.1.0-py2.7.egg/requests/__init__.pyc'
>>> requests.__path__
['/usr/local/lib/python2.7/dist-packages/requests-1.1.0-py2.7.egg/requests']
于 2013-08-30T18:47:35.183 回答
0

获取模块文件名而不加载它:

print(importlib.util.find_spec("urllib.request", None).origin)
于 2022-02-20T14:30:16.620 回答