'Find Python module filename

I got module name which contains declaration of os.path.isfile. Jedi lib gave me genericpath (without file path). Now i want to get full filename of PY file with this genericpath module. E.g. "C:\Py27\Lib\genericpath.py". How can I do it? Jedi cannot do it?



Solution 1:[1]

When __file__ doesn't work, do it the proper way—use inspect:

>>> import somemodule
>>> import inspect
>>> inspect.getfile(somemodule)
'/usr/lib64/python2.7/somemodule.pyc'

Solution 2:[2]

Like this:

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

For packages that are not part of the Python core, you can also use __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']

Solution 3:[3]

Get module filename without loading it:

print(importlib.util.find_spec("urllib.request", None).origin)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michael Scheper
Solution 2 Burhan Khalid
Solution 3 BaiJiFeiLong