Reputation: 4036
How can I get the absolute path of an imported module?
Upvotes: 24
Views: 26038
Reputation: 1237
If it is a module within your PYTHONPATH directory tree (and reachable by placing a __init__.py
in its directory and parent directories), then call its path attribute.
>>>import sample_module
>>>sample_module.__path__
['/absolute/path/to/sample/module']
Upvotes: 9
Reputation: 10116
As the other answers have said, you can use __file__
. However, note that this won't give the full path if the other module is in the same directory as the program. So to be safe, do something like this:
>>> import os
>>> import math
>>> os.path.abspath(math.__file__)
'/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/math.so'
Here's an example with a module I made called checkIP
to illustrate why you need to get the abspath (checkIP.py
is in the current directory):
>>> import os
>>> import checkIP
>>> os.path.abspath(checkIP.__file__)
'/Users/Matthew/Programs/checkIP.py'
>>> checkIP.__file__
'checkIP.py'
Upvotes: 44
Reputation: 1452
You can try:
import os
print os.__file__
to see where the module is located.
Upvotes: 3