我需要从被调用者那里获取调用者信息(什么文件/什么行).我了解到我可以使用inpect模块来达到目的,但不是如何.
如何通过检查获得这些信息?或者有没有其他方法来获取信息?
import inspect
print __file__
c=inspect.currentframe()
print c.f_lineno
def hello():
print inspect.stack
?? what file called me in what line?
hello()
Run Code Online (Sandbox Code Playgroud)
unu*_*tbu 86
呼叫者的帧比当前帧高一帧.您可以使用它inspect.currentframe().f_back来查找呼叫者的帧.然后使用inspect.getframeinfo获取调用者的文件名和行号.
import inspect
def hello():
previous_frame = inspect.currentframe().f_back
(filename, line_number,
function_name, lines, index) = inspect.getframeinfo(previous_frame)
return (filename, line_number, function_name, lines, index)
print(hello())
# ('/home/unutbu/pybin/test.py', 10, '<module>', ['hello()\n'], 0)
Run Code Online (Sandbox Code Playgroud)
Dmi*_* K. 43
我建议inspect.stack改用:
import inspect
def hello():
frame,filename,line_number,function_name,lines,index = inspect.stack()[1]
print(frame,filename,line_number,function_name,lines,index)
hello()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29821 次 |
| 最近记录: |