python – How to retrieve a modules path?

python – How to retrieve a modules path?

import a_module

Will actually give you the path to the .pyc file that was loaded, at least on Mac OS X. So I guess you can do:

import os
path = os.path.abspath(a_module.__file__)

You can also try:

path = os.path.dirname(a_module.__file__)

To get the modules directory.

There is inspect module in python.

Official documentation

The inspect module provides several useful functions to help get
information about live objects such as modules, classes, methods,
functions, tracebacks, frame objects, and code objects. For example,
it can help you examine the contents of a class, retrieve the source
code of a method, extract and format the argument list for a function,
or get all the information you need to display a detailed traceback.


>>> import os
>>> import inspect
>>> inspect.getfile(os)
>>> inspect.getfile(inspect)
>>> os.path.dirname(inspect.getfile(inspect))

python – How to retrieve a modules path?

As the other answers have said, the best way to do this is with __file__ (demonstrated again below). However, there is an important caveat, which is that __file__ does NOT exist if you are running the module on its own (i.e. as __main__).

For example, say you have two files (both of which are on your PYTHONPATH):

import bar


import os

Running will give the output:

/path1        # import bar causes the line print(os.getcwd()) to run
/path2/ # then print(__file__) runs
/path2/ # then the import statement finishes and print(bar.__file__) runs

HOWEVER if you try to run on its own, you will get:

/path2                              # print(os.getcwd()) still works fine
Traceback (most recent call last):  # but __file__ doesnt exist if is running as main
  File /path2/, line 3, in <module>
NameError: name __file__ is not defined 

Hope this helps. This caveat cost me a lot of time and confusion while testing the other solutions presented.

Leave a Reply

Your email address will not be published. Required fields are marked *