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]
精彩评论