How to retrieve a module's path? How to retrieve a module's path? python python

How to retrieve a module's path?

import a_moduleprint(a_module.__file__)

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 ospath = os.path.abspath(a_module.__file__)

You can also try:

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

To get the module's 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)'/usr/lib64/python2.7/os.pyc'>>> inspect.getfile(inspect)'/usr/lib64/python2.7/inspect.pyc'>>> os.path.dirname(inspect.getfile(inspect))'/usr/lib64/python2.7'

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):

#/path1/foo.pyimport barprint(bar.__file__)


#/path2/bar.pyimport osprint(os.getcwd())print(__file__)

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 fineTraceback (most recent call last):  # but __file__ doesn't exist if is running as main  File "/path2/", line 3, in <module>    print(__file__)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.