2

Possible Duplicate:
Retrieving python module path

Suppose I have code in 3 python files. x.py, y.py, z.py.

x calls y and y calls z. In the code in z.py, I want to know what directory x.py is in.

Is there a function that will tell me this?

EDIT forget z.py. I just want y.py to print out the path of x.py.
EDIT

Note that the system has 30 different files all named x.py located in different directories.

Community
  • 1
  • 1
user584583
  • 1,242
  • 4
  • 18
  • 35

3 Answers3

3

If the code in z.py has indirectly imported x.py, it will be in sys.modules. So try:

module = sys.modules.get('x')
if module is not None:
    print module.__file__
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • thanks for your answer. Somethings not working. Module is None. I edited my question. I don't care about z.py anymore. I just want y.py to print out the path of x.py. – user584583 Oct 12 '11 at 14:41
  • @user584583. it will only work if `x` has already been imported before `y` is. if x.py is the main script and imports `y`, it won't work, because `x` will not be imported. – ekhumoro Oct 12 '11 at 15:12
2

Import x and evaluate x.__file__.

0

In this circumstance those imports may lead to chain imports. So, in some functions namespace import main module.

def where_is_x():
    import __main__
    print __main__.__file__
Melug
  • 1,023
  • 9
  • 14