How to retrieve a module's path?


I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.

How do I retrieve a module's path in python?

1/10/2019 5:19:15 PM

Accepted Answer

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 module's directory.

8/15/2019 11:13:46 AM

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow