Wednesday, April 20, 2011

Getting file path of imported module

How can I get the file path of a module imported in python. I am using Linux (if it matters).

Eg: if I am in my home dir and import a module, it should return back the full path of my home directory.

From stackoverflow
  • This will give you the directory the module is in:

    import foo
    os.path.dirname(foo.__file__)
    
  • Modules and packages have a __file__ attribute that has its path information. If the module was imported relative to current working directory, you'll probably want to get its absolute path.

    import os.path
    import my_module
    
    print os.path.abspath(my_module.__file__)
    
  • I've been using this:

    import inspect
    import os
    class DummyClass: pass
    print os.path.dirname(os.path.abspath(inspect.getsourcefile(DummyClass))
    

    (Edit: This is a "where am I" function - it returns the directory containing the current module. I'm not quite sure if that's what you want).

  • To find the load path of modules already loaded:

    >>> import sys
    >>> sys.modules['os']
    <module 'os' from 'c:\Python26\lib\os.pyc'>
    

0 comments:

Post a Comment