How can I get the absolute path of an imported module?
3 Answers
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'
function_name.__code__works nicely at getting the full file path.