开发者

How do I find out in which file or module is my function called?

开发者 https://www.devze.com 2023-01-17 15:42 出处:网络
Python 2.5 to 2.7: #a.py: def foo(): pass #b.py from a import foo foo() From foo(), I\'d like to know that it has benn called in the \"b\" module. The onl开发者_如何学Pythony way I can think of ri

Python 2.5 to 2.7:

#a.py:
def foo():
    pass

#b.py
from a import foo
foo()

From foo(), I'd like to know that it has benn called in the "b" module. The onl开发者_如何学Pythony way I can think of right now is raising an exception, catching it and inspecting the traceback (going one level up). Is there a mare natural way of doing this?


You can do this with the inspect module.

E.g.

#!/usr/bin/env python
# a.py
import inspect

def foo():
    for item in inspect.stack():
        print item

-

#!/usr/bin/env python
# b.py

from a import foo

foo()

-

$ python b.py
(<frame object at 0x2026fb0>, '/home/tdb/a.py', 6, 'foo', ['    for item in inspect.stack():\n'], 0)
(<frame object at 0x1fe4a30>, 'b.py', 5, '<module>', ['foo()\n'], 0)


Nevermind, it turns out the solution is:

import traceback
traceback.extract_stack(limit=2))[0]
0

精彩评论

暂无评论...
验证码 换一张
取 消