Python: How to get absolute path of file in imported module
Question: I have imported a module as:

    
    
    from source.x.ReviseOnOrder import reviseOnX, x
    

The method `reviseOnX` runs another python script, say `y.py` which is in the
same location i.e `/source/x`. So, when executing `reviseOnX`, I'd like to
know the full path so that I can pass the correct path to subprocess that
calls `y.py`.

Based on other SO questions, I tried the following:

    
    
    print os.path(source.x.ReviseOnOrder.__file__)
    

But it gives the following error:

    
    
    NameError: global name 'source' is not defined
    

How can I find the correct path?


Answer: You only have references to objects imported from the module, you don't have
the module object itself.

Use the [`inspect.getmodule()`
function](https://docs.python.org/2/library/inspect.html#inspect.getmodule) to
get the module object again:

    
    
    import inspect
    
    mod = inspect.getmodule(reviseOnX)
    print os.path.abspath(mod.__file__)
    

Note that I am using `os.path.abspath()`, **not** `os.path()`. The latter
would try to call the module.

