Determinant
Determinant

Reputation: 4036

Find the absolute path of an imported module

How can I get the absolute path of an imported module?

Upvotes: 24

Views: 26038

Answers (3)

MrUser
MrUser

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

Matthew Adams
Matthew Adams

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

Taro Sato
Taro Sato

Reputation: 1452

You can try:

import os
print os.__file__

to see where the module is located.

Upvotes: 3

Related Questions